题解 | #牛牛的链表删除#
牛牛的链表删除
https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }; struct node* init_node(int data) { struct node* head = (struct node*)malloc(sizeof(struct node)); head->data = data; head->next = NULL; return head; } void push(struct node* head, int data) { struct node* new_node = init_node(data); struct node* p = head; while (p->next != NULL) { p = p->next; } p->next = new_node; } // void swap(struct node* head, int x, int y) { // if (head->data < x || head->data < y || x == y) { // return; // } // struct node* p = head, *q = head; // for (int i = 0; i < x; i++) { // p = p->next; // } // for (int i = 0; i < y; i++) { // q = q->next; // } // int temp = p->data; // p->data = q->data; // q->data = temp; // } void delete_by_data(struct node* head, int data) { if (head->data == 0) { return; } struct node* p = head; while (p->next != NULL) { if (p->next->data == data) { struct node* q = p->next; p->next = p->next->next; free(q); continue; } p = p->next; } } void print_list(struct node* head) { if (head->data == 0) { return; } struct node* p = head->next; while (p != NULL) { printf("%d ", p->data); p = p->next; } } int main() { int n, x; scanf("%d", &n); scanf("%d", &x); struct node* head = init_node(n); for (int i = 0; i < n; i++) { int var; scanf("%d", &var); push(head, var); } delete_by_data(head, x); print_list(head); if (head != NULL) { free(head); head = NULL; } }