typedef struct node
{
int date;
struct node *front,*next;
}_Node;
有两个双向循环链表A,B,知道其头指针为:pHeadA,pHeadB,请写一函数将两上链表中date值相同的结点删除
参考算法:
1.取出A的一个元素d
2.收集B中有相同元素d的结点到垃圾箱,并从B里删除
3.收集A中有相同元素d的结点到垃圾箱,并从A里删除
4.删除垃圾箱中的所有元素
5.A链的指针指向下一个
6.重复1~5,直到A链循环到头了
注意的是第3步,在2步执行后垃圾箱不为空时才执行。
上述算法还可以做一点点优化:
1.加入两个变量cA, cB,分别记录当前A中和B中的元素个数
每次从较长者中取出一个元素来,先从较小者中找起
若没有,则不必在较长者中浪费时间了
#include<iostream.h> ?
struct NODE
{
int date;
NODE *front,*next;
};
void redel(NODE *&ahead,NODE *&bhead)
{
int boy=0;
NODE *pa=ahead,*pb=bhead,*paa,*paaa,*paaaa,*pbb;
while(pa->next!=ahead)
{
int boys=pa->date; //取pa中一个值
paaaa=pa;
paa=pa;
pb=bhead;
while(pb->next!=bhead)
{
if(boys==pb->date) //如果pa,pb中有值相同
{
cout<<endl;
cout<<"delete B:"<<paa->date<<" ";
if(pb==bhead)
{
boy=1;
pb->front->next=pb->next;
pb->next->front=pb->front;
bhead=bhead->next;
pbb=pb;
pb=pb->next;
delete pbb;
}
else
{
boy=1;
pb->front->next=pb->next;
pb->next->front=pb->front;
pbb=pb;
pb=pb->next;
delete pbb;
}
}
else
pb=pb->next;
}
while(paa->next!=ahead && boy==1)
{
if(paa->date==boys)
{
cout<<"delete A:"<<paa->date<<" ";
if(paa==pa)
{
pa=pa->next;
ahead=pa;
paa->front->next=paa->next;
paa->next->front=paa->front;
paaa=paa;
paa=paa->next;
delete paaa;
}
else
{
paa->front->next=paa->next;
paa->next->front=paa->front;
paaa=paa;
paa=paa->next;
delete paaa;
}
}
else
{
paa=paa->next;
}
}
boy=0;
if(paaaa==pa)
pa=pa->next;
}
cout<<endl;
}
int main()
{
NODE *A,*pHeadA,*B,*pHeadB;
A=new NODE;
B=new NODE;
pHeadA=A;
pHeadB=B;
for(int i=1;i<21;++i) //生成链表A,并赋初值!
{
A->date=i;
A->next=new NODE;
A->next->front=A;
A=A->next;
}
A=A->front;
delete A->next;
A->next=pHeadA;
pHeadA->front=A;
for(int i=1;i<33;i+=2) //生成链表B,并赋初值!
{
B->date=i;
B->next=new NODE;
B->next->front=B;
B=B->next;
}
B=B->front;
delete B->next;
B->next=pHeadB;
pHeadB->front=B;
redel(pHeadA,pHeadB); //调用函数删除相同结点!
}