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 (≤105) 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
基本思路:不想写链表指针啥的,都用数组模拟 PAT链表的题目基本不会太重,能模拟出来即可
详细思路:
先录入链表,当然多保存一个字段->当前地址
然后正常索引式遍历链表,按序将链表复制一份到Node ans[]数组(不用order字段排序了,复制后直接有序了)
最后K个K个逆置(我的G就是K),每次逆置一个都存到vector里,最后一起输出(不然next不好输出)
坑点1:可能有结点不在链表上,也即遍历到next=-1了,该结点尚未遍历到,这种结点字节丢弃
坑点2:K个K个逆置,最后剩下少于K个不逆置,直接接到尾部,但是开始表长总共就不够K个时(也即
开始就剩下不到K个),此时却需要逆置!
易错用例:
输入:
00000 6 4
00000 1 11111
11111 2 22222
22222 3 -1
33333 4 44444
44444 5 55555
55555 6 -1
输出:
22222 3 11111
11111 2 00000
00000 1 -1
输入:
00100 6 2
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出:
12309 2 00100
00100 1 00000
00000 4 33218
33218 3 68237
68237 6 99999
99999 5 -1
AC源码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std;
struct Node {
int address, data, next;
}node[100010],ans[100010];
int head, N, G;
int main() {
//freopen("in.txt", "r", stdin);
cin >> head >> N >> G;
int add, data, next, T = N;
while (T--) {//N要留下
cin >> add >> data >> next;
node[add].address = add;
node[add].data = data;
node[add].next = next;
}
T = 0;
for (int i = head;i != -1;i = node[i].next) {
ans[T++] = node[i];
}
vector<Node> ve;
for (int i = 0;i<T;i+=G) {//可能有无效结点 此时不能用N只能用T
if (i + G<=T||i==0) {//开始就剩不到G个,需要逆置
for (int j = min(i + G - 1,T-1);j >= i;j--) ve.push_back(ans[j]);
}else {//最后结尾剩下不到G个不需要逆置
for (int j = i;j < T;j++) ve.push_back(ans[j]);
}
}
for(vector<Node>::iterator it=ve.begin();it!=ve.end();it++){
printf("%05d %d ", it->address, it->data);
if (it != ve.end() - 1) printf("%05d\n", (it + 1)->address);
else printf("-1\n");
}
return 0;
}