输出时,依据编号获得对应的值
#include <iostream>
#include <iomanip>
using namespace std;
const int N = 100010;
int st, n;
int e[N], ne[N];
int a[N], cnt;//按链表遍历顺序存每个数的编号
void add(int x, int y, int w){
e[x] = w, ne[x] = y;
}
int main(){
cin >> st >> n;
for(int i = 1; i <= n; i ++ ){
int a, b, c;
cin >> a >> b >> c;
add(a, c, b);
}
for(int i = st; i != -1; i = ne[i]){
a[ ++ cnt] = i;
}
for(int i = 1, j = cnt; i <= cnt / 2; i ++ ){//这里用cnt而不用n是因为并不一定所有的节点都在给定的链表中
cout << setfill('0');
cout << setw(5) << a[j] << " " << e[a[j]] << " " << setw(5) << a[i] << endl;
j -- ;
if(i >= j) break;
cout << setw(5) << a[i] << " " << e[a[i]] << " " << setw(5) << a[j] << endl;
}
cout << setfill('0');
int u = cnt / 2;
if(cnt % 2 == 1) u ++ ;//链表中节点数为奇数时,最终链表输出的最后一个数是 cnt / 2 + 1
cout << setw(5) << a[u] << " " << e[a[u]] << " " << -1 << endl;
return 0;
}