有双向循环链表结点定义为:
struct node
{
int data;
struct node *front,*next;
};
有两个双向循环链表A,B,知道其头指针为:pHeadA,pHeadB,请写一函数将两链表中data值相同的结点删除。
#include<iostream.h>
#include<malloc.h>
struct node
{
int data;
node *front,*next;
};
node* creatlist(int a[],int len) //建立带头结点的双循环链表
{
node *head=(node *)malloc(sizeof(node));
head->front=head;
head->next=head;
for(int i=0;i<len;i++)
{
if(i==0)
{
node *p=(node *)malloc(sizeof(node));
p->data=a[i];
p->next=head->next;
head->next=p;
p->front=head;
head->front=p;
}
else
{
node *p=(node *)malloc(sizeof(node));
p->data=a[i];
p->next=head->next;
head->next->front=p;
head->next=p;
p->front=head;
}
}
return head;
}
void printlist(node *head) // 遍历双循环链表
{
node *p=head->next;
while(p&&p!=head)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void deletesamenodeone(node *pheadA,node *pheadB) //双循环while遇到相同的就删除
{
if(pheadA==NULL||pheadB==NULL)
return;
node *p=pheadA->next;
while(p&&p!=pheadA)
{
int f=0;
node *q=pheadB->next;
while(q&&q!=pheadB)
{
if(p->data==q->data)
{
f=1;
node *d=q;
q=q->next;
d->front->next=d->next;
d->next->front=d->front;
delete(d);
}
else
q=q->next;
}
if(f==1)
{
node *d=p;
p=p->next;
d->front->next=d->next;
d->next->front=d->front;
delete(d);
}
else
p=p->next;
}
}
void deletesamenodetwo(node *pheadA,node *pheadB) //先排序,找到相同元素,然后遍历各个链表删除这些元素
{
//这里就不写了
}
void main()
{
int a[5]={3,10,2,1,8},b[6]={6,8,3,12,10,2};
node *pheadA=NULL,*pheadB=NULL;
pheadA=creatlist(a,sizeof(a)/sizeof(int));
pheadB=creatlist(b,sizeof(b)/sizeof(int));
printlist(pheadA);
printlist(pheadB);
deletesamenodeone(pheadA,pheadB);
printlist(pheadA);
printlist(pheadB);
}