#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <map>
using namespace std;
const int maxn=100010;
struct Node
{
char data;
int next;
}node[maxn];
int main()
{
freopen("1.txt","r",stdin);
int h1,h2,n;
scanf("%d%d%d",&h1,&h2,&n);
for(int i = 0;i < n;i++)
{
int ind,nextn;
char a;
scanf("%d %c %d",&ind,&a,&nextn);
node[ind].data = a;
node[ind].next = nextn;
}
int ans;
int flag = 0; //为1代表发现共同地址
//解法1 一个节点超时
// node[-1].next = -1;
// while(h1!=-1)
// {
// int h22 = h2; //确保链表2每次都是从头开始遍历
// while(h22!=-1)
// {
//
// if(node[h1].next == node[h22].next) //如果他们的后继节点是同一个
// {
// ans = node[h1].next; //记录最前面的相同节点
// flag = 1; //找到答案
// break;
// }
// h22 = node[h22].next;
// }
// if(flag == 1) //找到答案就退出
// break;
// h1 = node[h1].next;
// }
//解法2
int trail1[maxn],trail2[maxn]; //路径1和路径2
int ind1 = 0,ind2 = 0;
while(h1!=-1) //分别记录链表的路径
{
trail1[ind1++] = h1;
h1 = node[h1].next;
}
while(h2!=-1)
{
trail2[ind2++] = h2;
h2 = node[h2].next;
}
if(trail1[ind1 - 1] != trail2[ind2 - 1]) //从最后节点开始遍历 如果相同则有解
{
flag = 0;
}
else
{
flag = 1;
for(int i = ind1 - 1;i>=0;i--)
{
if(trail1[i] == trail2[ind2 - 1])
{
ans = trail1[i];
ind2--;
}
}
}
if(flag == 1)
printf("%d",ans);
else
printf("-1");
return 0;
}
1032 Sharing (25分)
最新推荐文章于 2021-09-26 13:44:13 发布