链表题几乎是PAT出现频率最高的题型之一,这种解法一般在50行内。而且扩展性强,个人感觉比《算法笔记》这一类题的解法要好。
然后就是一个悲催的故事,我PAT97的原因就是链表题有一个样例没过,因为少了一行代码n = coun;
,QAQ
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.
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值对链表进行反转。
容我先给出代码:
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
using namespace std;
int data[100010],Next[100010];
int order[100010];
int main() {
int frist,n,k;
cin >> frist >> n >> k;
for(int i=0;i<n;i++){
int address;
cin >> address;
cin >> data[address] >> Next[address];
}
int temp = frist;
int coun = 0;
while(temp != -1){
order[coun++] = temp;
temp = Next[temp];
}
n = coun;
for(int i=0;i+k<=n;i+=k){
reverse(order+i,order+k+i);
}
for(int i=0;i<n;i++){
int now = order[i];
if(i == n-1)
printf("%05d %d -1\n",now,data[now]);
else
printf("%05d %d %05d\n",now,data[now],order[i+1]);
}
return 0;
}
一、定义和初始化
记住定义三个数组data[],Next[],order[]
。
- data存储输入的数据,即索引为地址,数组值为数值。
- Next存储下一个地址,即索引为地址,数组值为下一个地址。
- order顺序存储了链表,即索引为链表索引,数组值为地址,什么意思呢?就是你完全可以按照处理数组的方法,处理order。
二、根据输入设置data、Next
直接看代码,没什么好说的。
三、从第一个地址开始,顺序保存地址到order
直接看代码,有个大坑。n = coun;
因为不一定所有的输入的结点都是有用的,不加这个一般会挂一个用例。
四、处理order,打印结果
直接看代码,还是有坑,注意%05d打印,这样会在前面补0。还有就是最后一元素的下一个地址为-1。
总结,作者水平有限,有哪里有问题都欢迎评论指出。如果对你有帮助欢迎点赞。