A1032 Sharing (25point(s))
题意
给出两条链表并找出共同后缀,输出节点地址,如果没有则输出-1.
思路
建立两条链表倒着遍历。
11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010
Sample Output:
00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1
#include"bits/stdc++.h"
using namespace std;
const int maxn = 100010;
struct Node{
int addr;
int next = -1;
};
Node nodes[maxn];
int main(){
// freopen("input.txt","r",stdin);
int head1,head2,n;
cin >> head1 >> head2 >> n;
for(int i=0;i<n;i++){
int addr,next; char e;
scanf("%d %c %d",&addr,&e,&next);
nodes[addr].addr = addr;
nodes[addr].next = next;
}
int t1 = head1;
list<int> a1;
while(nodes[t1].next != -1) {
a1.push_back(t1); t1 = nodes[t1].next;
}
int t2 = head2;
list<int> a2;
while(nodes[t2].next != -1) {
a2.push_back(t2); t2 = nodes[t2].next;
}
if(a1.empty() || a2.empty()){
cout << -1 << endl;
return 0;
}
int ans = -1;
while(!a1.empty() && !a2.empty() &&a1.back() == a2.back()){
ans = a1.back();
a1.pop_back();
a2.pop_back();
}
if(ans == -1)
printf("-1\n");
else
printf("%05d\n",ans);
}