问题:发现重复元素,则删除全部重复元素,如:给定:2 3 3 3 5 7 8 8 8 8 9 9 10 输出:2 5 7 10
解法:若q->next的值和q的值相等,则将q->next->next赋值给p,删除q;重复上述过程直至链表尾端。
#include<bits/stdc++.h>
using namespace std;
struct node
{
int val;
node *next;
node(int v):val(v),next(NULL){}
};
void print(node *hea)
{
node *p=hea->next;
int f=0;
while(p)
{
if(f)
printf(" ");
printf("%d",p->val);
p=p->next;
f=1;
}
printf("\n");
}
void qc(node *hea)
{
node *p=hea,*q=hea->next,*pre;
while(q)
{
int f=0;
pre=q->next;
while(pre&&pre->val==q->val)
{
delete q;
q=pre;
pre=pre->next;
f=1;
}
if(f)
{
p->next=pre;
delete q;
}
else
p=q;
q=pre;
}
print(hea);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
node *tail,*p,*hea;
int num;
hea=new node(0);
tail=new node(0);
for(int i=0;i<n;i++)
{
scanf("%d",&num);
p=new node(num);
tail->next=p;
tail=p;
if(i==0)
{
p->next=hea->next;
hea->next=p;
}
}
qc(hea);
}
return 0;
}