题解 | 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;
    }
}

全部评论

相关推荐

10-17 13:54
上海大学 运营
雾凇岛:这还说什么了,冲了兄弟们
点赞 评论 收藏
分享
敢逐云霄志:你打招呼语怎么能这么长,hr都没看下去的欲望,简明扼要说重点,就读于某某学校某某专业,26届应届毕业生,学信网可查,先后在某某公司实习过(如有),然后做过什么项目,想找一份什么样的工作,可实习几个月以上,期待您的回复。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务