PAT A1052

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

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
55
56
#include "stdio.h"
//#include "math.h"
#include "string.h"
//#include "iostream"
#include "stdlib.h"
//#include "vector"
//#include "set"
//#include "map"
#include "algorithm"
using namespace std;

//typedef long long LL;
const int maxn = 100010;
struct NODE{
int next, data, address;
bool flag;//结点在链表中是否出现
}node[maxn];

bool cmp(NODE a, NODE b){
if (a.flag == false || b.flag == false) {
return a.flag > b.flag;
}else{
return a.data < b.data;//递增排序
}
}
int main(){
for (int i = 0; i < maxn; i++) {
node[i].flag = false;//没有在第一条链表出现
}
int n, begin, count = 0;//s1,s2分别代表两条链表的首地址
scanf("%d%d", &n, &begin);
int address;//结点地址与下一结点地址
for (int i = 0 ; i < n; i++) {
scanf("%d", &address);
scanf("%d%d", &node[address].data, &node[address].next);
node[address].address = address;
}
for (int p = begin; p != -1; p = node[p].next) {
node[p].flag = true;//枚举第一条链表的所有结点,令其出现次数为1
count++;
}
if (count == 0) {
printf("0 -1");//特判,新链表中没有结点时输出0 -1
}else{
sort(node, node + maxn, cmp);
printf("%d %05d\n", count, node[0].address);
for (int i = 0; i < count; i++) {
if (i != count - 1) {
printf("%05d %d %05d\n", node[i].address, node[i].data, node[i+1].address);
}else{
printf("%05d %d -1\n",node[i].address, node[i].data);
}
}
}
return 0;
}

  • 链表的题最好画一下
  • 这题排序后,地址也变动,所以需要记录各个结点自己的地址,在输出的时候,输出自己的地址和下一个结点的地址(而不是本结点的next)
  • 输出地址的时候要注意,-1不能使用%05d输出,否则会输出-0001(而不是-1或者-00001),因此必须要留意-1的输出。
  • 数据里面还有均为无效的情况,这是就要根据有效结点的个数特判输出”0 -1”