题解 | #牛牛的链表删除#
牛牛的链表删除
https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }node; node *createlist() { node *head = malloc(sizeof(node)); if(head == NULL) { printf("out of memory"); exit(1); } head->next = NULL; return head; } void add_node(node *head, int n, int *p) //用尾插法建立链表 { node *cur = head; for(int i = 0; i < n; i++) { node *newnode = malloc(sizeof(node)); if(newnode == NULL) { printf("out of memory"); exit(1); } newnode->data = p[i]; //新建节点并赋值 newnode->next = NULL; //新建节点指针域置为空 cur->next = newnode; //连接新节点 cur = newnode; //移动流指针 } } node *delet_node(node *head, int x) { node *p = head; node *q = p->next; while(q != NULL) { if(q->data == x) { p->next = q->next; free(q); q = p->next; //注意这里删除q所指向的元素之后q要重新赋值 } else { p = q; //没有找到要删除的元素p先向后移动 q = q->next; //q也向后移动 } } return head; } int main() { int n,x; scanf("%d %d",&n, &x); int arr[n]; for(int i = 0; i < n; i++) { scanf("%d", &arr[i]); } node *head = createlist(); //创建空链表 add_node(head,n, arr); //添加数组元素用尾插法插入数组中 node *newhead = delet_node(head, x); //删除链表中元素x; node *current = newhead->next; while(current != NULL) //遍历输出链表的每个元素 { printf("%d ",current->data); current = current->next; } printf("\n"); return 0; }