PAT(A) 1133. Splitting A Linked List (25)

原题目:

原题链接:https://www.patest.cn/contests/pat-a-practise/1133

1133. Splitting A Linked List (25)


Given a singly linked list, you are supposed to rearrange its elements so that all the negative values appear before all of the non-negatives, and all the values in [0, K] appear before all those greater than K. The order of the elements inside each class must not be changed. For example, given the list being 18→7→-4→0→5→-6→10→11→-2 and K being 10, you must output -4→-6→-2→7→0→5→10→18→11.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 105) which is the total number of nodes, and a positive K (<=1000). The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer in [-105, 105], and Next is the position of the next node. It is guaranteed that the list is not empty.

Output Specification:

For each case, output in order (from beginning to the end of the list) the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:
00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218
Sample Output:
33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1

题目大意

输入是地址,数据,下一地址。按序输出,并先输出负数,再输出小于等于K的非负数,再输出大于K的正数,按原链表顺序输出。

解题报告

注意输出格式。先读入后,分3次输出需要输出的数据。如果用cin,cout有可能会在最后一个点超时。

代码

1133. Splitting A Linked List (25)
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
57
58
59
60
61
62
63
64
65
66
67
/*
* Problem: 1133. Splitting A Linked List (25)
* Author: HQ
* Time: 2018-03-13
* State: Done
* Memo: 链表
*/
#include "iostream"
#include "vector"
using namespace std;

struct Node {
int data;
int next;
};

int N,K;
int start;
vector<struct Node> addrs;

int main() {
scanf("%d %d %d", &start, &N, &K);
int x;
int add, next;
addrs.resize(1000000);
for (int i = 0; i < N; i++) {
scanf("%d %d %d", &add, &x, &next);
struct Node temp = { x,next };
addrs[add] = temp;
}
bool first = true;
int s = start;
while (s != -1) {
if (addrs[s].data < 0) {
if (first)
first = false;
else
printf(" %05d\n", s);
printf("%05d %d", s, addrs[s].data);
}
s = addrs[s].next;
}
s = start;
while (s != -1) {
if (addrs[s].data >= 0 && addrs[s].data <= K) {
if (first)
first = false;
else
printf(" %05d\n", s);
printf("%05d %d", s, addrs[s].data);
}
s = addrs[s].next;
}
s = start;
while (s != -1) {
if (addrs[s].data > K) {
if (first)
first = false;
else
printf(" %05d\n", s);
printf("%05d %d", s, addrs[s].data);
}
s = addrs[s].next;
}
cout << " -1"<< endl;
system("pause");
}