{
printf("请输入要删除的学生姓名")
char k[100]
scanf("%s", k)
struct node *pre = NULL
struct node *q = head
while (q) {
if (strcmp(q->data.name, k) == 0){
if (pre)
pre->next = q->next
else
head = q->next
free(q)
break
}
pre = q
q = q->next
}
return head
}
这种删除方法是头节点存放值的,这样可以清楚的看到是否删除掉了头节点。
用p保存头节点 p=head
head指向下一个节点,成为新的头节点 head=p->next
释放原来的头节点 free(p)
#include<iostream>#include<stdio.h>
#include <stdlib.h>
void printList(struct node *head)
struct node* delHead(struct node *head)
struct node{
int data
struct node* next
}
int main(){
int i
struct node *tail,*head,*p
//尾插法插入数据
p=(struct node*)malloc(sizeof(struct node))
p->data=0
tail=head=p
tail->next=NULL
for(i=1i<10i++){
p=(struct node*)malloc(sizeof(struct node))
tail->next=p
p->data=i
p->next=NULL
tail=p
}
printList(head)
head=delHead(head)
printList(head)
system("pause")
return 0
}
//删除头结点
struct node* delHead(struct node *head){
struct node *p = head
head=p->next
free(p)
return head
}
//打印链表
void printList(struct node *head){
struct node *p = head
while (p != NULL){
printf("%i ", p->data)
p = p->next
}
printf("\n")
}