//链表中节点的特点在于,其每个节点包括一个值和志向的下一个指针,因此,一旦某一个节点相同,则该节点之后的所有节点都会相同。本程序实际上比较的是节点值相同则结束,并不是真正的指针相同。事实上,自己构造也很麻烦,并不适合自己实现。初始输入的结构应当是前端分叉,后端合一(有相同节点)的两个链表。
#include <iostream>
#include <string>
#include <stdio.h>
using
namespace
std;
struct
Entry
{
string m;
Entry *next;
};
Entry *GetNewEntry(){
string p;
cin>>p;
Entry *newOne=
new
Entry;
newOne->m=p;
newOne->next=NULL;
return
newOne;
}
Entry *BuildList(
int
n)
{
Entry *listHead=NULL;
Entry *p=NULL;
while
(n>0)
{
Entry *newOne=GetNewEntry();
//if(newOne==NULL) break;
//if (n==0) break;
n--;
if
(p==NULL)
{
p=newOne;
listHead=p;
}
else
{
//newOne->next=p;
//p->next=newOne;
//p=p->next;
p->next=newOne;
p=p->next;
}
}
return
listHead;
}
int
length(Entry *listHead)
{
int
n=0;
Entry *p;
p=listHead;
while
(p!=NULL)
{
n++;
p=p->next;
}
return
n;
}
string findthefirst(Entry *list1,Entry *list2)
{
Entry *m,*n;
m=list1;
n=list2;
while
(m->m!=n->m&&m->next!=NULL)
{
m=m->next;
n=n->next;
}
if
(m->next==NULL||n->next==NULL)
{
if
(m->m==n->m)
{
return
m->m;
}
else
{
return
"My God"
;
}
}
else
{
return
m->m;
}
}
int
main()
{
int
m,n;
int
difference;
string result;
while
(cin>>m>>n)
{
Entry *list1=BuildList(m);
Entry *list2=BuildList(n);
Entry *p=list1;
Entry *q=list2;
int
length1=length(list1);
int
length2=length(list2);
if
(length1>length2)
{
difference=length1-length2;
while
(difference!=0)
{
p=p->next;
difference--;
}
result=findthefirst(p,q);
}
else
if
(length1==length2){
result=findthefirst(p,q);
}
else
{
difference=length2-length1;
while
(difference!=0)
{
q=q->next;
difference--;
}
result=findthefirst(p,q);
}
cout<<result<<endl;
}
}
/**************************************************************
Problem: 1505
User: 无梦楼主lv
Language: C++
Result: Accepted
Time:170 ms
Memory:8780 kb
****************************************************************/