您的位置:首页 > 其它

两个链表的第一个公共节点

2014-07-25 09:35 309 查看
//此题可以使用栈解决,但空间复杂度需要考虑。。。
//也可根据两个链表长度之差解决~~
#include<iostream>
using namespace std;
typedef struct Node
{
int data;
Node *next;
}lnode,*list;
list listinit()
{
list L;
L=(lnode*)malloc(sizeof(list));
if(L==NULL)
cout<<"没有足够的内存空间!"<<endl;
L->next=NULL;
return L;
}
list listcreateTail()//Tail
{
int i,len,data;
list L,p,r;
L=(lnode*)malloc(sizeof(list));
L->next=NULL;
r=L;
cout<<"input the length of this list:"<<endl;
cin>>len;
cout<<"input the data of this list:"<<endl;
//	cin>>data;
for(i=0;i<len;i++)
{
cin>>data;
p=(lnode*)malloc(sizeof(list));
p->data=data;
r->next=p;
r=p;

}
r->next=NULL;
return L;
}
list reverse(list L)
{
list p,q;
p=L->next;

L->next=NULL;
while(p)
{
q=p->next;
p->next=L->next;
L->next=p;
p=q;

}
return L;
}
int CommonNode(list L1,list L2)
{
L1=reverse(L1);
L2=reverse(L2);
if(L1==NULL || L2==NULL)
return ;
int temp;
list p,q;
p=L1->next;
q=L2->next;
while(p->data==q->data)
{
temp=p->data;
p=p->next;
q=q->next;

}
return temp;
}
void output(list L)
{
list p;
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
}
int main()
{
list L,Lr,L1,L2;
int k;
L1=listcreateTail();
output(L1);
cout<<endl;
L2=listcreateTail();
output(L2);
cout<<endl;
cout<<CommonNode(L1,L2);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: