题目:
数据结构实验之链表七:单链表中重复元素的删除
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic Discuss
Problem Description
按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。
Input
第一行输入元素个数 n (1 <= n <= 15);
第二行输入 n 个整数,保证在 int 范围内。
Output
第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。
Sample Input
10
21 30 14 55 32 63 11 30 55 30
Sample Output
10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21
Hint
Source
不得使用数组!
代码:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node*create(int n)
{
struct node *head,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
int i;
for(i=1; i<=n; i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
}
return head;
}
void print(struct node*h)
{
struct node*p;
p=h->next;
while(p!=NULL)
{
if(p==h->next)
{
printf("%d",p->data);
}
else
{
printf(" %d",p->data);
}
p=p->next;
}
printf("\n");
}
int main()
{
int n;
scanf("%d",&n);
struct node*h;
h=create(n);
printf("%d\n",n);
print(h);
struct node *p,*t,*q;
q=h->next;
while(q!=NULL)
{
t=q;//定义一个指针跟在查找指针q的后面跑
p=q->next;
while(p!=NULL)
{
if(p->data==q->data)
{
t->next=p->next;
p=p->next;//此处也要有一个前进
n--;
}
else
{
p=p->next;
t=t->next;
}
}
q=q->next;
}
printf("%d\n",n);
p=h->next;
while(p!=NULL)
{
if(p==h->next)
{
printf("%d",p->data);
}
else printf(" %d",p->data);
p=p->next;
}
printf("\n");//这个输出是个技巧,有的不用区分后面的空格是不是要带,有的就要分析,所以最好区分开
return 0;
}
关键部分:
就是定义一个跟在比较 指针后面的指针,然后进行删除
关键是怎么保留住有相同元素的?外循环就保留了,内循环只是删除
代码2:
只用两个指针的算法
#include<stdio.h>
#include<stdlib.h>
int n;
struct node
{
int data;
struct node*next;
};
struct node*create(int n)
{
struct node*head,*p;
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
int i;
for(i=1;i<=n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=head->next;
head->next=p;
}
return head;
}
void dele(struct node*head)
{
struct node*p,*q;
p=head->next;
while(p)
{
q=p;
while(q->next)//对于这里我们一直的操作是q先不变,去比较q->next,如果,举个栗子,像如果碰到和p->data相等的数了,这时候是q->next=q->next->next,但这时候q还是没变的呀,下一步比较的时候还是q->next->data,就是比较的相等的这位数紧邻的后面的数,如果这个数不和p->data相等,那就q=q->next,q就挪动的这个数上了,下一步比较的还是q->next,所以我们的判断条件写的就是q->next
{
if(q->next->data==p->data)
{
q->next=q->next->next;
n--;
}
else q=q->next;
}
p=p->next;
}
}
void print(struct node*head)
{
struct node*p;
p=head->next;
while(p)
{
if(p==head->next)
{
printf("%d",p->data);
}
else printf(" %d",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
struct node*h;
scanf("%d",&n);
h=create(n);
printf("%d\n",n);
print(h);
dele(h);
printf("%d\n",n);
print(h);
return 0;
}