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 (<105) 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 [−105,105], 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
题目大意
题目给定一个静态链表,将其按照键值递增顺序重新排列并输出。
解题思路
- 在储存节点时除了数据和下一跳地址信息以外增加一个有效位,表明该节点是否有效(在链表中);
- 读入各节点并记录其地址,并遍历一遍,记录节点有效性;
- 重新排序并输出(注意有效节点个数为0的边界条件);
- 返回零值。
代码
#include<cstdio>
#include<algorithm>
#define maxn 100010
using namespace std;
struct Node{
int address,data,flag,next;
}node[maxn];
bool cmp(Node a,Node b){
if(a.flag!=b.flag){
return a.flag>b.flag;
}else{
return a.data<b.data;
}
}
int main(){
int num=0;
int N,head;
int id,data,next;
int i;
scanf("%d%d",&N,&head);
for(i=0;i<N;i++){
scanf("%d%d%d",&id,&data,&next);
node[id].address=id;
node[id].data=data;
node[id].next=next;
}
while(head!=-1){
num++;
node[head].flag=1;
head=node[head].next;
}
sort(node,node+maxn,cmp);
head=node[0].address;
if(num==0){
printf("0 -1\n");
}else{
printf("%d %05d\n",num,head);
}
for(i=0;i<num;i++){
printf("%05d %d ",node[i].address,node[i].data);
if(i==num-1){
printf("-1\n");
}else{
printf("%05d\n",node[i+1].address);
}
}
return 0;
}
运行结果