链表合并

清华大学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;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值