PAT 甲级 A1074

1074 Reversing Linked List (25分)

题目描述

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

输入格式

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤ 1 0 5 10^{​5} ) which is the total number of nodes, and a positive K (≤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 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.

输出格式

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

总结

  1. 题目大概意思就是说以K位来反转链表,最后不足K位的则不用反转。
  2. 这题我也不想搞那么多,直接用个最容易想的办法写了。题目给的很容易想到用静态链表来存储,不过我还开了个额外的空间来保存结果数组,也算是以空间换时间吧。这种以空间换时间的真的太适合我这种菜逼了QWQ。思路就是遍历原来的数组,把有效的结点一个个加入到新开的数组里面,直接调用reverse反转,就OK了,这题既要注意5位输出,也要注意地址-1时需要特判输出

AC代码

#include <iostream>
#include<algorithm>
using namespace std;
struct node {
	int addr, data, next;
}linkList[100005];
node ans[100005];
int main(){
	int s, n, reverseL, addr, len = 0;
	scanf("%d%d%d", &s, &n, &reverseL);
	while (n--) {
		scanf("%d", &addr);
		linkList[addr].addr = addr;
		scanf("%d %d", &linkList[addr].data, &linkList[addr].next);
	}
	for (int i = s; i != -1; i = linkList[i].next) ans[len++] = linkList[i];
	
	for (int i = 0; i < len; i+=reverseL) {
		if (i + reverseL <= len) {
			reverse(ans + i, ans + i + reverseL);
		}	
	}
	for (int i = 0; i < len - 1; i++) {
		printf("%05d %d %05d\n", ans[i].addr, ans[i].data, ans[i + 1].addr);
	}
	printf("%05d %d -1\n", ans[len - 1].addr, ans[len - 1].data);
	return 0;
}
发布了24 篇原创文章 · 获赞 3 · 访问量 1732

猜你喜欢

转载自blog.csdn.net/qq_38507937/article/details/104341300
今日推荐