单链表中重复元素删除

http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2122

 1 #include<stdio.h>  
 2 #include<stdlib.h>  
 3 typedef struct node  
 4 {  
 5     int data;  
 6     struct node *next;  
 7 }lb;  
 8 lb *creat(int n)  //建立逆序链表  
 9 {  
10     int i;  
11     lb *head,*p;  
12     head=(lb*)malloc(sizeof(lb));  
13     head->next=NULL;  
14     for(i=0;i<n;i++)  
15     {  
16         p=(lb*)malloc(sizeof(lb));  
17         scanf("%d",&p->data);  
18         p->next=head->next;  
19         head->next=p;  
20     }  
21     printf("%d\n",n);  
22     return head;  
23 }  
24 void list(lb *r)   //输出原表
25 {  
26     lb *q;  
27     q=r;  
28     while(q->next->next!=NULL)  //输出
29     {  
30         printf("%d ",q->next->data);  
31         q=q->next;  
32     }  
33     printf("%d\n",q->next->data);  
34 }  
35 void del(lb *head,int n)  //删除相同元素
36 {  
37     lb *p,*q1,*q2;  
38     p = head;  
39     while(p->next!=NULL)  
40     {  
41         q1 = p;  
42         q2 = p->next;  
43         while(q2!=NULL)  
44         {  
45             if(p->data==q2->data)  
46             {  
47                 q1->next=q2->next;  
48                 q2=q2->next;  
49                 n--;  
50             }  
51             else  
52             {  
53                 q1=q1->next;  
54                 q2=q2->next;  
55             }  
56         }  
57         p=p->next;  
58     }  
59     p=head;  
60     printf("%d\n",n);  
61     while(p->next->next!=NULL)  //输出
62     {  
63         printf("%d ",p->next->data);  
64         p=p->next;  
65     }  
66     printf("%d\n",p->next->data);  
67 }  
68 int main()  
69 {  
70     lb *head;  
71     int n;  
72     scanf("%d",&n);   
73     head=creat(n);  
74     list(head);  
75     del(head,n);  
76     return 0;  
77 }  

 

posted @ 2013-03-11 20:37  海东青飞吧!  阅读(232)  评论(0编辑  收藏  举报