1052 Linked List Sorting (25分)
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
分析
将链表中的节点按照key值排序。
-
用结构体存储节点,flag记录该节点是否在链表中;
用sort方法进行排序,cmp方法:两个节点都访问过则从小到大排序,否则把没访问过的节点放后面。
-
输入的N是内存中节点的总个数,不一定所有节点都在链表里!!输出的N是链表中节点的总个数。
-
注意:节点的下址,排序后是发生变化的。
-
注意:当链表中节点个数为0时,输出为
0 -1
,和其他时候不同。 -
注意:最后一个节点的下址的输出和别的下址输出格式不同
代码
#include<iostream>
#include<algorithm>
using namespace std;
struct NODE {
int addr,data,next;
bool flag;//记录该节点是否在链表中
} node[100000];
int cmp1(NODE a,NODE b) {
return a.flag&&b.flag?a.data<b.data:a.flag>b.flag;
}
int main() {
int n,start;//n为总结点个数
int count=0;//链表节点个数
scanf("%d %d",&n,&start);
//存放数据
int addr,data,next;
for(int i=0; i<n; i++) {
scanf("%d %d %d",&addr,&data,&next);
node[addr]= {addr,data,next,false};
}
//遍历链表,设置flag,计算count
for(int i=start; i!=-1; i=node[i].next) {
node[i].flag=true;
count++;
}
if(count==0) {
printf("0 -1");
} else {
//排序
sort(node,node+100000,cmp1);
//输出
printf("%d %05d
",count,node[0].addr);
for(int i=0; i<count; i++) {
printf("%05d %d ",node[i].addr,node[i].data);
if(i==count-1)
printf("-1
");
else
printf("%05d
",node[i+1].addr);
}
}
return 0;
}
问题
-
count变量放在开头定义和就近定义的答案不一样;int默认值是0,但我打印了一下count输出是1,可能是堆栈数据残留。
解决:以后变量全在开头定义,并且自己赋初值。