PAT甲级刷题之路——1074

是一道链表链表题,继续刷题,冲冲冲!

有点像今年秋季的PAT甲级的第二题,说多了都是泪呀

PAT1074 Reversing Linked List

原题如下

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.
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 (≤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.
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位。然后输出翻转后的链表。

自己的想法

因为节点数不超过 1 0 5 10^5 105,所以完全可以用静态链表(即数组)储存。然后把这一个链表压入vector中然后再用reverse函数翻转前k位(不是前k位,我第一次理解错了,应该是每k位翻转一次!!),最后输出。嘿嘿我真是个小天才(允许小白的我沾沾自喜一下,希望不要报错啊喂!!

答案反馈

第一次提交:
啊啊啊,我想起今天PAT那道和这个类似的题好像也错了6分的测试点,把这题debug成功应该能收获不少吧!GOGOGO!!
PAT甲级刷题之路——1074_第1张图片
回宿舍了,室友该睡觉了,明天早起debug!!
错误的点:
唔,看错题了,题中说的是每k位要翻转一次,我第一次提交只翻转了前k位,看清题啊喂!!
PAT甲级刷题之路——1074_第2张图片

代码

附上AC的代码啦~

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<set>
#include<queue>
#include<map>
#include<stack>
using namespace std;
const int maxn = 100005;
struct node {
	int ad, data, next;
}link[maxn];
vector<node> v;
void build_vector(int root) {
	if (root == -1) { return; }
	v.push_back(link[root]);
	build_vector(link[root].next);
}
int main() {
	int st, N, k;
	cin >> st >> N >> k;
	for (int i = 0; i < N; i++) {
		int s, data, e;
		cin >> s >> data >> e;
		link[s].ad = s; link[s].data = data; link[s].next = e;
	}
	build_vector(st);//用来将链表压进vector中方便翻转
	int num = v.size() / k;//首先求出要翻转多少段
	for (int i = 0; i < num; i++) {
		reverse(v.begin()+i*k, v.begin() + i*k+k);
	}
	for (int i = 0; i < v.size()-1; i++) {
		printf("%05d %d %05d\n", v[i].ad, v[i].data, v[i + 1].ad);
	}
	printf("%05d %d -1\n", v[v.size()-1].ad, v[v.size()-1].data);
	return 0;
}

结语

看清题目看清题目!!千万不要操之过急!!
小白上路,可能有很多错误的地方,欢迎大家指出,一起交流呀~

你可能感兴趣的:(PAT甲级刷题之路)