PAT甲级1074
题目描述
Given a constant K K K and a singly linked list L L L, you are supposed to reverse the links of every K K K elements on L L L. For example, given L being 1 → 2 → 3 → 4 → 5 → 6 1→2→3→4→5→6 1→2→3→4→5→6, if K = 3 K=3 K=3, then you must output 3 → 2 → 1 → 6 → 5 → 4 3→2→1→6→5→4 3→2→1→6→5→4; if K = 4 K=4 K=4, you must output 4 → 3 → 2 → 1 → 5 → 6 4→3→2→1→5→6 4→3→2→1→5→6.
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 N N( ≤ 1 0 5 ≤10^5 ≤105) which is the total number of nodes, and a positive K K K ( ≤ N ≤N ≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N N 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, and Next
is the position of the next node.
Output Specification:
For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample Output:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
思路分析
题意是让我们反转链表中每
K
K
K个元素组成的子表。首先明确应该用什么数据结构来存储链表的信息。考虑到题目给出的输入数据中,链表的地址是整型数字,所以不妨用数组来存储链表,并用数组下标代表结点的地址。每个结点保存数据域和next
。
至于反转链表,可以先实现反转一个链表的函数,再反复调用此函数就可以了。
注意点
- 输入数据中可能存在无效结点。
- 对于 − 1 -1 −1应当特判。
C++ 程序
#include <iostream>
struct Node {
int data;
int next;
} list[1000001];
int head, N, K, addr, count = 0;
// return the first node of the remain list
int ReverseList(int& prev) {
int link = list[prev].next;
for (int i = 1; i < K; ++i) {
int tmp = list[link].next;
list[link].next = prev;
prev = link;
link = tmp;
}
return link;
}
int main() {
scanf("%d%d%d", &head, &N, &K);
for (int i = 0; i < N; ++i) {
scanf("%d", &addr);
scanf("%d%d", &list[addr].data, &list[addr].next);
}
for (int p = head; p != -1; p = list[p].next) ++count;
int m = count / K, last = head, prev = head;
for (int i = 0; i < m; ++i) {
int x = prev;
int link = ReverseList(prev);
if (i == 0) head = prev;
else list[last].next = prev;
last = x;
prev = link;
}
list[last].next = prev;
for (int p = head; p != -1; p = list[p].next) {
printf("%05d %d ", p, list[p].data);
list[p].next != -1 ? printf("%05d\n", list[p].next) : printf("-1\n");
}
return 0;
}