Description |
输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。 |
Input |
第一行输入数据个数n; 第二行依次输入n个整数; 第三行输入欲删除数据m。 |
Output |
第一行输出原始单链表的长度; 第二行依次输出原始单链表的数据; 第三行输出完成删除后的单链表长度; 第四行依次输出完成删除后的单链表数据。 |
Sample Input |
10 56 25 12 33 66 54 7 12 33 12 12 |
Sample Output |
10 56 25 12 33 66 54 7 12 33 12 7 56 25 33 66 54 7 33 1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<malloc.h> 4 5 int n; 6 int m; 7 8 typedef struct Node 9 { 10 int data; 11 struct Node *next; 12 } ListNode; 13 14 ListNode *Init(void) 15 { 16 ListNode *head = NULL; 17 head = (ListNode *)malloc(sizeof(ListNode)); 18 /* 19 if (head==NULL) 20 { 21 return NULL; 22 } 23 */ 24 head->next = NULL; 25 return head; 26 } 27 28 void CreatList(ListNode *listhead) 29 { 30 int x; 31 ListNode *p = NULL; 32 ListNode *r = NULL; 33 if (!listhead) 34 { 35 return; 36 } 37 r = listhead; 38 //p = listhead->next; 39 for (int i=0; i<n; i++) 40 { 41 p = (ListNode*)malloc(sizeof(ListNode)); 42 scanf("%d", &x); 43 p->data = x; 44 r->next = p; 45 r = p; 46 } 47 r->next = NULL; 48 } 49 50 void DeletElem(ListNode *listhead) 51 { 52 int i = 0; 53 ListNode *p = NULL; 54 ListNode *q = NULL; 55 if (!listhead) 56 { 57 return; 58 } 59 p = listhead; 60 for (i=0; i<n; i++) 61 {while (p->next && p->next->data!=m) 62 { 63 p = p->next; 64 } 65 if (p->next) 66 { 67 q = p->next; 68 p->next = q->next; 69 free(q); 70 n--; 71 } 72 else 73 { 74 return; 75 } 76 } 77 } 78 79 void TravList(ListNode *listhead) 80 { 81 ListNode *p = NULL; 82 if (!listhead) 83 { 84 return; 85 } 86 p = listhead->next; 87 while (p) 88 { 89 if (p->next!=NULL) 90 { 91 printf("%d ",p->data); 92 } 93 else 94 { 95 printf("%d\n", p->data); 96 } 97 p = p->next; 98 } 99 } 100 101 void DestoryList(ListNode *listhead) 102 { 103 ListNode *p = NULL; 104 ListNode *s = NULL; 105 if (!listhead) 106 { 107 return; 108 } 109 p = listhead; 110 while (p) 111 { 112 s = p->next; 113 free(p); 114 p = s; 115 } 116 } 117 118 int main(void) 119 { 120 //int n, m; 121 while (scanf("%d", &n)!= EOF) 122 { 123 int k = n; 124 ListNode *head = NULL; 125 head = Init(); 126 CreatList(head); 127 //TravlList(head); 128 scanf("%d", &m); 129 printf("%d\n", k); 130 TravList(head); 131 DeletElem(head); 132 printf("%d\n", n); 133 TravList(head); 134 DestoryList(head); 135 } 136 return 0; 137 } 138 void Delete(LinkList L,int x)//删除值为x的结点 139 { 140 LinkList p,q; 141 p=L; 142 while( p->next &&p->next->data!=x) 143 p=p->next; 144 if(p->next) 145 { 146 q=p->next; 147 p->next=q->next; 148 free(q); 149 printf("删除成功!!\n\n"); 150 } 151 else 152 printf("链表中没有%d\n\n",x); 153 }
|