清华大学1995。
已知三个带头结点的线性链表A,B,C中的结点均依照自小到大非递减排列(可能存在两个以上值相同的结点),编写算法对A表进行如下操作:使操作后的链表A中仅存留三个表中均包含的元素的结点,且没有值相等的结点,并释放所有无用的结点。限定算法的时间复杂度为O(m+n+p),其中m,n,p分别为三个单链表的长度。
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node *build(node* p)
{
int n;
cin>>n;
p=(node*)malloc(sizeof(node));
node *r,*q;
r=p;
r->next=NULL;
while(n--)
{
q=(node*)malloc(sizeof(node));
cin>>q->data;
r->next=q;
r=q;
r->next=NULL;
}
return p;
}
node* func(node* A,node *B,node *C)
{
node *pre,*p,*q,*r,*x;
pre=A;
A->data=100000000;//监视哨
p=A->next;
q=B->next;
r=C->next;
while(p!=NULL&&q!=NULL&&r!=NULL)
{
if(pre->data==p->data)
{
x=p;
pre->next=p->next;
p=pre->next;
free(x);
continue;
}
if(p->data<q->data||p->data<r->data)
{
x=p;
pre->next=p->next;
p=pre->next;
free(x);
}
else if(p->data>q->data||p->data>r->data)
{
if(p->data>q->data)
q=q->next;
if(p->data>r->data)
r=r->next;
}
else {
pre=p;
p=p->next;
q=q->next;
r=r->next;
}
}
pre->next=NULL;
while(p)
{
node *z;
z=p;
p=p->next;
free(z);
}
return A;
}
void print(node *A)
{
node *p;
p=A->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
while(1)
{
node *A=0,*B=0,*C=0;
A=build(A);
B=build(B);
C=build(C);
A=func(A,B,C);
print(A);
}
return 0;
}