题解 | Sharing

Sharing

https://www.nowcoder.com/practice/2577bea713cf4eed874afccff1928113

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct node {
    int pos;
    char data;
    int next;
    node(int pos, char data, int next) :pos(pos), data(data), next(next) {
    }
    node(){}
};


int main()
{
    int start1, start2, n;
    while (cin >> start1 >> start2 >> n) {
        unordered_map<int, node>edge;
        for (int i = 0; i < n; i++) {
            int pos, next;
            char data;
            cin >> pos >> data >> next;
            edge.insert({ pos,node(pos,data,next) });
        }
        int len1 = 0, len2 = 0;
        //先遍历链表一
        int ptr1 = start1;
        while (ptr1 != -1) {
            ptr1 = edge[ptr1].next;
            len1++;
        }
        int ptr2 = start2;
        while (ptr2 != -1) {
            ptr2 = edge[ptr2].next;
            len2++;
        }
        ptr1 = start1, ptr2 = start2;
        //然后长度那个先走几步
        while (len1 > len2)ptr1 = edge[ptr1].next, len1--;
        while (len1 < len2)ptr2 = edge[ptr2].next, len2--;
        bool isame = false;
        while (ptr1 != -1 && ptr2 != -1) {
            if (edge[ptr1].pos == edge[ptr2].pos) {
                cout << edge[ptr1].pos << endl;
                isame = true;
                break;
            }
            ptr1 = edge[ptr1].next, ptr2 = edge[ptr2].next;
        }
        if (isame == false)cout << -1 << endl;
    }
}

全部评论

相关推荐

牛客ID:561366855:期望薪资多少?难以相信这简历找不到工作。说明二本电子信息专业想对口就业非常难。
点赞 评论 收藏
分享
头像
05-16 11:16
已编辑
东华理工大学 Java
牛客737698141号:盲猜几十人小公司,庙小妖风大,咋不叫她去4️⃣呢😁
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务