1032 Sharing (25分)

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值