链表中重复元素的删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{
struct node *head,*p;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
for(int i=0;i<n;i++)
{
p=(struct node *)malloc(sizeof(struct node ));
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
}
return head;
};
void show (struct node *head)
{
struct node *p;
p=head->next;
while(p)
{
if(!p->next)
{
printf("%d\n",p->data);
}
else
{
printf("%d ",p->data);
}
p=p->next;
}
}
void del(struct node *&head,int &n)
{
struct node *q,*p,*t;
p=head->next;
while(p)
{
t=q; //上t在p的位置上
q=p->next; //让q代表遍历的指针
while(q)
{
if(q->data==p->data) //当查找到重复的元素的时候
{
t->next=p->next;
n--;
p=p->next;
}
else
{
t=t->next;
p=p->next;
}
}
q=q->next;
}
}
int main()
{
struct node *head;
int n;
scanf("%d",&n);
head=creat(n);
printf("%d\n",n);
show(head);
del(head,n);
printf("%d\n",n);
show(head);
}
Fork me on GitHub