它的测试数据有可能有分裂节点,所以需要计算实际所给链表的长度
#include<bits/stdc++.h>
using namespace std;
struct Node{
int val;
int next;
}x[100005];
int main(){
int j=0;
int start;
int n;
int ad1,num,ad2;
cin>>start>>n;
for(int i=0;i<n;i++){
cin>>ad1>>num>>ad2;
x[ad1].val=num;
x[ad1].next=ad2;
}
/*解决多余节点的代码*/
int first=start;
while(first!=-1)
{
first=x[first].next;
j++;
}
n=j;
/*解决多余节点的代码*/
int p=start;
vector<int> pre;
vector<int> post;
int mid=n/2;
int count=1;
// cout<<x[0].val<<" "<<x[0].next<<endl;
// cout<<x[100].val<<" "<<x[100].next<<endl;
while(p!=-1){
if(count<=mid){
pre.push_back(p);
}
else{
post.push_back(p);
}
p=x[p].next;
count++;
}
int ori=mid;
vector<int> res;
if(n % 2==0){
while(mid){
res.push_back(post[mid-1]);
res.push_back(pre[ori-mid]);
mid--;
}
}else{
while(mid){
res.push_back(post[mid]);
res.push_back(pre[ori-mid]);
mid--;
}
res.push_back(post[0]);
}
for(int i=0;i<n-1;i++){
printf("%05d %d %05d\n",res[i],x[res[i]].val,res[i+1]);
}
printf("%05d %d -1",res[n-1],x[res[n-1]].val);
return 0;
}