将链表中值为x的结点删除。
#include <stdio.h> #include <stdlib.h> //将链表中值为x的结点删除 //结点 struct linkNode{ int data; struct linkNode *next; }; void output(struct linkNode *head); //打印链表数据域 struct linkNode *creat_link_list_rear(int *a, int n); //尾插法 struct linkNode *delete_node(struct linkNode *h, int x); //删除指定值的结点 int main() { int a[6]; //存放结点数据 int x; //待删除数据 struct linkNode *head; //头指针(尾插法) printf("输入数组各元素的值【6个】:\n"); for(int i=0; i<6; i++){ scanf("%d", &a[i]); } head = creat_link_list_rear(a, 6); //尾插法 printf("此链表各个节点的数据为:\n"); output(head); printf("输入要删除的数据:\n"); scanf("%d", &x); head = delete_node(head, x); printf("\n插入新数据后,此链表各个节点的数据为:\n"); output(head); return 0; } //尾插法 struct linkNode *creat_link_list_rear(int a[], int n){ struct linkNode *h = NULL; //新建链表h,将每个结点依次插入到链尾,将链表的头指针返回 struct linkNode *s; //要插入的结点 struct linkNode *r; //尾结点 for(int i=0; i<n; i++){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i]; s->next = NULL; if(h == NULL){ h = s; }else{ r->next = s; } r = s; //r指向当前链表的尾结点 } return h; //返回链表头指针 } //删除指定值的结点 struct linkNode *delete_node(struct linkNode *h, int x){ struct linkNode *p; //游标 struct linkNode *pre; //p的前驱 p = h; while (p && x != p->data){ pre = p; p = p->next; } if (p){ //p非空(找到了要删除的结点) if (p == h){ //删除节点在链首 h = p->next; }else{ //删除节点在链中 pre->next = p->next; } } return h; } //打印链表数据 void output(struct linkNode *head){ struct linkNode *p = head; while (p){ printf("%d ", p->data); p = p->next; } printf("\n"); }