代码
#include<bits/stdc++.h>
using namespace std;
unordered_map<int,pair<int,int>> L, L2;
int reverse(int h) {
int p = h;
int prev = -1;
while(p != -1) {
int nxt = L[p].second;
L[p].second = prev;
prev = p;
p = nxt;
}
return prev;
}
void printfList(unordered_map<int,pair<int,int>> & l, int h) {
int p = h;
while(p != -1) {
int nxt = l[p].second;
if(nxt != -1) {
printf("%05d %d %05d\n", p, l[p].first, nxt);
} else
printf("%05d %d -1\n", p, l[p].first);
p = nxt;
}
}
int getLen(int h) {
int p = h;
int cnt = 0;
while(p != -1) {
int nxt = L[p].second;
++cnt;
p = nxt;
}
return cnt;
}
int main() {
int head1,head2, N;
cin >> head1 >> head2 >> N;
for(int i = 0; i < N; ++i) {
int p, val, next;
cin >> p >> val >> next;
L[p] = {val, next};
}
int len1 = getLen(head1);
int len2 = getLen(head2);
if(len1 < len2)
swap(head1, head2);
head2 = reverse(head2);
int p1 = head1, p2 = head2;
int cnt = 0;
int last = -1000;
while(p1 != -1 || p2 != -1) {
if(cnt > 0 && cnt % 2 == 0 && p2 != -1) {
L2[last].second = p2;
last = p2;
L2[last] = {L[p2].first, -1};
p2 = L[p2].second;
cnt = 0;
} else {
L2[last].second = p1;
last = p1;
L2[last] = {L[p1].first, -1};
p1 = L[p1].second;
++cnt;
}
}
printfList(L2, head1);
}