sdut 数据结构实验之链表七:单链表中重复元素的删除

题目描述

按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。

输入

第一行输入元素个数n;
第二行输入n个整数。

输出

第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。

示例输入

10
21 30 14 55 32 63 11 30 55 30

示例输出

10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21

提示

 

来源

不得使用数组!
 1 #include<stdio.h>
 2 #include<malloc.h>
 3 struct node
 4 {
 5     int data;
 6     struct node *next;
 7 };
 8 struct node *creat(int n)
 9 {
10     struct node *head,*p;
11     int i;
12     head = (struct node *)malloc(sizeof(struct node));
13     head->next = NULL;
14     for(i = 1;i <= n;i++)
15     {
16         p = (struct node *)malloc(sizeof(struct node));
17         scanf("%d",&p->data);
18         p->next = head->next;
19         head->next = p;
20     }
21     return head;
22 }
23 int main()
24 {
25     struct node *head,*p,*p1,*p2,*t,*m;
26     int n;
27     scanf("%d",&n);
28     head = creat(n);
29     t = head;
30     printf("%d\n",n);
31     while(t->next != NULL)
32     {
33         if(t->next->next == NULL)
34         {
35             printf("%d",t->next->data);
36         }
37         else
38         {
39             printf("%d ",t->next->data);
40         }
41         t = t->next;
42     }
43     printf("\n");
44     p = head;
45     while(p->next != NULL)
46     {
47         p1 = p;
48         p2 = p->next;
49         while(p2 != NULL)
50         {
51             if(p->data == p2->data)
52             {
53                 p1->next = p2->next;
54                     p2 = p2->next;
55                     n--;
56             }
57             else
58             {
59                 p1 = p1->next;
60                 p2 = p2->next;
61             }
62         }
63         p = p->next;
64     }
65     m = head;
66     printf("%d\n",n);
67     while(m->next != NULL)
68     {
69         if(m->next->next==NULL)
70         {
71             printf("%d",m->next->data);
72         }
73         else
74         {
75             printf("%d ",m->next->data);
76         }
77         m = m->next;
78     }
79     printf("\n");
80     return 0;
81 }

 

posted @ 2013-05-02 15:21  幺小妖_  阅读(282)  评论(0编辑  收藏  举报