A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (<10^5) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by −1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [−10^5
,10^5 ], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
Output Specification:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=110000;
//这题有个大坑的地方:有些node甚至可能都不在链表中...
struct NODE{
int add,data,next;
bool flag;//flag在链表里是个好东西,用来判断是不是,存不存在这类问题很有帮助
}node[maxn];
bool cmp(NODE a,NODE b){//对cmp的理解不够深啊,这次又差点跑偏了,再好好理解一下
if(a.flag!=true||b.flag!=true)
return a.flag>b.flag;
/*
1.直接写a.flag,不能写node[a].flag。因为cmp括号里已经表明了是在对a,b进行比较:搞情况形参和实参嗷
2.不要糊涂了,这个语句的意思并不是分flag分别为true和false的三种情况,
而是说,在 a.flag!=true||b.flag!=true的情况下,按flag从真到假依次排序(因为1>0)
这样就可以把不在链表中的node放在后面去,输出的时候就可以直接忽略了
*/
else
return a.data<b.data;
//这就是a.flag!=true||b.flag!=true不成立的情况了,也就是判断对象都在链表中,我们对它按data从小到大进行排序
}
int main(){
int n,start;
cin>>n>>start;
int add,data,next;
for(int i=0;i<n;i++){//链表题三部曲:输入,遍历+判断,排序输出
cin>>add>>data>>next;
node[add]={add,data,next,false};
}
int cnt=0;
for(int i=start;i!=-1;i=node[i].next){
node[i].flag=true;
cnt++;
}
if(cnt==0) printf("0 -1");
else{
sort(node,node+maxn,cmp);
/*
1.这里我曾经写成了node+n。这个n是代表了node的个数,但是本题中的node地址并不是连续的,所以需要遍历所有maxn个node
2.sort(node[0],node[8],cmp);这种写法是错误的!
*/
printf("%d %05d\n",cnt,node[0].add);
for(int i=0;i<cnt;i++){
printf("%05d %d ",node[i].add,node[i].data);
if(i<cnt-1) printf("%05d\n",node[i+1].add);
//错写成了printf("%05d\n",node[i].next);这里最后一个要接上下一个node的地址啊,不能直接输出当前node的next
else printf("-1\n");
}
}
return 0;
}