1052 Linked List Sorting

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:

1
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:

1
2
3
4
5
6
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345

Sample Output:

1
2
3
4
5
6
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1

浅析

静态链表的排序。把无效结点全部放后面去,然后有效节点根据数据大小排序。即 cmp 先比较一级 flag, 再比较二级 key。注意在结点排序过程中会改变结点在数组中的位置,因此不能用数组下标,每个节点需要保存自己的地址。注意链表的实际长度!!

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include 
#include
using namespace std;
const int MAXN=100010;
struct node{
int key, address, next;
bool flag;
} linknode[MAXN];
bool cmp(node a,node b){
if(a.flag == false || b.flag == false)
return a.flag > b.flag;
else
return a.key < b.key;
}
int main(){
int n, head;
scanf("%d%d",&n,&head);
//注意此处直接判断n是错的,坑!
//再实际输入的过程中,可能中间结点的next会等于-1
//即输入的链表其实是断的,所以链表的实际长度要另外统计
// if(!n){
// printf("0 -1\n");
// return 0;
// }
for (int i = 0; i < MAXN;i++)
linknode[i].flag = false;
int address, next, key;
for (int i = 0; i < n;i++){
scanf("%d %d %d",&address,&key,&next);
linknode[address].address = address;
linknode[address].key = key;
linknode[address].next = next;
// linknode[address].flag = true;
}
int count = 0, p;
for (p = head; p != -1;p=linknode[p].next)
{
count++;
linknode[p].flag = true;
}
if(count == 0){
printf("0 -1\n");
return 0;
}
sort(linknode, linknode + MAXN, cmp);
for (int i = 0; i < n-1;i++)
linknode[i].next = linknode[i+1].address;
linknode[n - 1].next = -1;
printf("%d %05d\n", count, linknode[0].address);
for (int i = 0;i-1;i++)
printf("%05d %d %05d\n", linknode[i].address, linknode[i].key, linknode[i].next);
printf("%05d %d -1\n", linknode[count-1].address, linknode[count-1].key);
return 0;
}
丨fengche丨 wechat
来找我聊天吧~
-------------本文结束感谢您的阅读-------------