题意:给定两个单词,以及存储的链表,求出他们第一个公共的结点地址。
tip:遍历记录单词a,再查单词b是否存在遍历过的结点
#include <iostream>
using namespace std;
struct {
int next;
bool flag;
} node[100003];
int main() {
int d1,d2,n;
cin>>d1>>d2>>n;
for(int i=0; i<n; i++) {
int t1,t2;
char ch;
cin>>t1>>ch>>t2;
node[t1]= {t2,false};
}
while(d1!=-1) {//遍历链表a,标记遍历过的结点
node[d1].flag=true;
d1=node[d1].next;
}
while(d2!=-1) {//遍历链表b,查看是否已被遍历过
if(node[d2].flag) {
printf("%05d",d2);
return 0;
}
d2=node[d2].next;
}
printf("-1");
return 0;
}