PAT 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

给定一系列结点,要求将它排序。 题目给出的结点是以5位数的头地址和5位数的尾地址组成的,所以开一个10w的数组,根据数组的下标索引可以很方便的找到结点的下一个结点。 代码如下:

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
#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

struct Node {
int key, address, next;
};

int main() {
int n = 0, head = 0, m = 0;
scanf("%d %d", &n, &head);
vector<struct Node> v(100000);
for (int i = 0; i < n; i++) {
struct Node t;
scanf("%d %d %d", &t.address, &t.key, &t.next);
v[t.address] = t;
}
struct Node *nodes = new struct Node[n];
for (int i = 0; head != -1; i++) {
nodes[m++] = v[head];
head = v[head].next;
}
qsort(nodes, m, sizeof(nodes[0]), [](const void *a, const void *b) {
const struct Node arg1 = *static_cast<const struct Node *>(a);
const struct Node arg2 = *static_cast<const struct Node *>(b);

if (arg1.key > arg2.key) return 1;
return -1;
});

if (m != 0) {
printf("%d %05d\n", m, nodes[0].address);
for (int i = 0; i < m; i++) {
if (i != m - 1)
printf("%05d %d %05d\n", nodes[i].address, nodes[i].key, nodes[i + 1].address);
else
printf("%05d %d -1\n", nodes[i].address, nodes[i].key);
}
} else {
cout << 0 << " -1";
}
delete[] nodes;
return 0;
}