1. 程式人生 > >2122=數據結構實驗之鏈表七:單鏈表中重復元素的刪除

2122=數據結構實驗之鏈表七:單鏈表中重復元素的刪除

eof n) stdio.h for div printf code main 元素

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 struct node
 4 {
 5     int data;
 6     struct node *next;
 7 };
 8 int main()
 9 {
10     int n,i;
11     scanf("%d",&n);
12     int count=n;
13     struct node*head,*p,*q,*k;
14     head=(struct node*)malloc(sizeof(struct
node)); 15 head->next=NULL; 16 for(i=0; i<n; i++) 17 { 18 p=(struct node*)malloc(sizeof(struct node)); 19 scanf("%d",&p->data); 20 p->next=head->next; 21 head->next=p; 22 }//逆序建立鏈表。 23 printf("%d\n",count); 24 for(p=head->next; p; p=p->next)
25 { 26 printf("%d",p->data); 27 if(p->next!=NULL)printf(" "); 28 } 29 printf("\n"); 30 for(p=head->next; p; p=p->next) 31 { 32 for(q=p; q->next!=NULL; ) 33 { 34 if(p->data==q->next->data) 35 {
36 k=q->next->next; 37 q->next=k; 38 count--; 39 } 40 else q=q->next; 41 } 42 }//註意一下這裏的的範圍,不然很容易超出範圍去訪問。 43 printf("%d\n",count); 44 for(p=head->next; p; p=p->next) 45 { 46 printf("%d",p->data); 47 if(p->next!=NULL)printf(" "); 48 } 49 return 0; 50 }

2122=數據結構實驗之鏈表七:單鏈表中重復元素的刪除