题解 | 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道真题和解析