1.定义三个指针变量*p,*q,*t,p先指向第一个要扫描的结点.
2.判断链表中是否存在和p一样的结点,让q指向p,判断q的next结点是否和p相同,如果相同(1)让t指向这个结点.(2)让q的next指向t的next.(3)销毁t所指向的结点
3.如果q的next结点不于p结点相同,则让q向后移动,既q=q->next;
4.判断完当前p结点后,让p结点后移。
#include <iostream>
#include<stdlib.h>
using namespace std;
struct node
{
int x;
struct node *next;
};
//顺序建表
struct node *creatListShun(int lenth)
{
struct node *head,*t,*p;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
t=head;
for(i=0; i<lenth; i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->x=i%7;
p->next=NULL;
t->next=p;
t=p;
}
return head;
}
//链表删除重复
struct node *delSame(struct node *head1)
{
struct node *t,*p,*q;
p=head1->next;
while(p)
{
q=p;
while(q->next)
{
if(q->next->x==p->x)
{
t=q->next;
q->next=t->next;
free(t);
}
else
q=q->next;
}
p=p->next;
}
return head1;
};
int main()
{
struct node *head1,*t1;
head1=creatListShun(10);//顺序建链表
t1=head1->next;
cout<<"顺序建链表 :";
while(t1!=NULL)
{
cout<<t1->x<<" ";
t1=t1->next;
}
cout<<endl;
//删除重复
head1=delSame(head1);
t1=head1->next;
cout<<"链表删除重复"<<endl;
while(t1)
{
cout<<t1->x<<" ";
t1=t1->next;
}
return 0;
}