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

来源:互联网 发布:淘宝做单一个月挣多少 编辑:程序博客网 时间:2024/06/06 00:57
//此题可以使用栈解决,但空间复杂度需要考虑。。。
//也可根据两个链表长度之差解决~~
#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;}

0 0