AC代码
#include<stdio.h>
typedef struct{
int add;
int data;
int next;
}node;
int main(){
int fir,n,k,c=0;
node origin[100000],sort[100000],temp;
scanf("%d %d %d",&fir,&n,&k);
for(int i=0;i<n;i++){
scanf("%d %d %d",&temp.add,&temp.data,&temp.next);
origin[temp.add]=temp;//用下标表示地址
}
temp=origin[fir];//第一次遍历,先找小于0的结点,连接成新的链表
while(1){
if(temp.data<0)sort[c++]=temp;
if(temp.next==-1)break;
else temp=origin[temp.next];
}
temp=origin[fir];//第二次遍历,找<=k的结点,在链表尾部连接
while(1){
if(temp.data>=0&&temp.data<=k)sort[c++]=temp;
if(temp.next==-1)break;
else temp=origin[temp.next];
}
temp=origin[fir];//第三次遍历,找>k的结点,在链表尾部连接
while(1){
if(temp.data>=0&&temp.data>k)sort[c++]=temp;
if(temp.next==-1)break;
else temp=origin[temp.next];
}
for(int i=0;i<c;i++){
if(i!=c-1){//重置next域,再输出
sort[i].next=sort[i+1].add;
printf("%05d %d %05d\n",sort[i].add,sort[i].data,sort[i].next);
}
if(i==c-1){//最后节点的next域置为-1
sort[i].next=-1;
printf("%05d %d %d\n",sort[i].add,sort[i].data,sort[i].next);
}
}
return 0;
}