单链表结点删除
1 /* 2 QQ:778138708 3 date:2020年5月15日 4 单链表结点删除 5 */ 6 #include <stdio.h> 7 #include <stdlib.h> 8 9 struct ListNode { 10 int data; 11 struct ListNode *next; 12 }; 13 struct ListNode *readlist(void); 14 struct ListNode *deletem(struct ListNode *L, int m); 15 void printlist(struct ListNode *L); 16 int main(void) 17 { 18 int m; 19 20 struct ListNode *L = readlist(); 21 scanf("%d", &m); 22 L = deletem(L, m); 23 printlist(L); 24 25 return 0; 26 } 27 //新建一个链表 28 struct ListNode *readlist(void) 29 { 30 struct ListNode *head, *tail, *p; 31 int n; 32 33 head = tail = NULL; 34 scanf("%d", &n); 35 while (n != -1) { 36 p = (struct ListNode *)malloc(sizeof(struct ListNode)); 37 p->data = n; 38 p->next = NULL; 39 40 if (head == NULL) { 41 head = tail = p; 42 } else { 43 tail->next = p; 44 tail = tail->next; 45 } 46 47 scanf("%d", &n); 48 } 49 50 return head; 51 } 52 //删除,其实是跳过需要删除的结点,重新生成一个新的链表 53 struct ListNode *deletem(struct ListNode *L, int m) 54 { 55 struct ListNode *head, *tail, *p, *temp; 56 57 head = tail = NULL; 58 p = L; 59 60 while (p) { 61 temp = p; 62 p = p->next; 63 if (temp->data != m) { 64 if (head == NULL) { 65 head = temp; 66 head->next = NULL; 67 tail = head; 68 } else { 69 tail->next = temp; 70 tail = tail->next; 71 tail->next = NULL; //tail等于temp,所以tail->next = NULL 72 } 73 } 74 } 75 //返回新的链表头 76 return head; 77 } 78 void printlist(struct ListNode *L) 79 { 80 struct ListNode *p = L; 81 82 while (p) { 83 printf("%d ", p->data); 84 p = p->next; 85 } 86 87 printf("\n"); 88 }