[PAT解题报告] Reversing Linked List
简单题,每k个元素一组翻转链表。链表给的形式比较有意思,PAT的题链表都如此给。就是地址、元素值(一般是整数)、下一个元素的地址或者-1表示空,其实和指针真正的指针没什么区别的。
做法也比较直接,注意如果长度对k取余数非0,最后那几个是不动的。
(1)先计算链表长度n
(2)循环出最近k个元素,截断,得到一个长度恰好为k的链表,和剩余部分,注意维护好两部分的表头
(3) 翻转长度为k的链表
(4) 把(3)翻转的结果接到之前保存的结果上
(5) 转(2)
(6) 如果有“尾巴”,接到之前的结果上。
关键问题,每次连接注意可能当前结果就是第一段,之前可能是空。包括(6)的连接也是如此,因为链表可能根本就不足k个元素。
代码:
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
struct node {
int val;
int next;
};
node a[100005];
int reverse(node *a, int head) {
int answer = -1;
while (head >= 0) {
int next = a[head].next;
a[head].next = answer;
answer = head;
head = next;
}
return answer;
}
int main() {
int n, head, k;
scanf("%d%d%d",&head, &n, &k);
for (int i = 0; i < n; ++i) {
int ad;
scanf("%d",&ad);
scanf("%d%d",&a[ad].val,&a[ad].next);
}
int tail = -1, answer = -1;
n = 0;
for (int i = head; i >= 0; ++n, i = a[i].next)
;
for (int i = 0, j ; n >= k;) {
for (i = head, j = k - 1; j ;i = a[i].next, --j)
;
n -= k;
j = a[i].next;
a[i].next = -1;
int temp = reverse(a, head);
head = j;
if (tail < 0) {
answer = tail = temp;
}
else {
a[tail].next = temp;
}
for (tail = temp; a[tail].next >= 0; tail = a[tail].next)
;
}
if (tail < 0) {
answer = tail = head;
}
else {
a[tail].next = head;
}
for (int i = answer; i >= 0; i = a[i].next) {
printf("%05d %d ", i, a[i].val);
if (a[i].next >= 0) {
printf("%05d\n",a[i].next);
}
else {
puts("-1");
}
}
return 0;
}
原题链接: http://www.patest.cn/contests/pat-a-practise/1074

查看28道真题和解析
