1025 反转链表
给定一个常数 K 以及一个单链表 L,请编写程序将 L 中每 K 个结点反转。
例如:给定 L 为 1→2→3→4→5→6,K 为 3,则输出应该为 3→2→1→6→5→4;
如果 K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K 个元素不反转。
每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N (≤10^5)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:Address Data Next
其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。
#include <iostream>
#include <algorithm>
using namespace std;
int K = 0;
const int maxn = 111111; // Maximum of input value
// 用来存储数值和下一节点的地址
struct nodes{
int next;
int value;
};
int main(){
// 临时变量,存储头节点的地址,节点数量,K的数值
int head = 0, total = 0;
cin >> head >> total >> K;
// 主变量,以当前节点的地址为索引,存储一组数值和下一节点的地址 store value and next addresses
nodes node[maxn];
// 主变量,用来存储节点在链表中的顺序(节点地址的次序)store addresses
int addresses[total];
// 关键是意识到输入数据的特点:找到每个节点间的连接 The Key is to build a connection between randomized addresses and values
// 从头节点地址开始,把它与对应的节点数值和下一节点地址连接 Start from head address, link head address to corresponding value and its next address
// 依次进行 Then find the value linked by the next address, and so on
// 因为节点本身的数值和地址不能改变,所以只能改变节点的“下一节点地址” Since one value links to one constant address, we could only modify the sequence of values by changing their "next addresses"
int i = 0, address = 0;
while (i < total){
// Use node's address as index, store value and original next address to the node
// 当前节点地址 当前节点数值 当前节点的下一节点地址
cin >> address >> node[address].value >> node[address].next;
i++;
}
// 将节点的下一节点地址拷贝到另一个数组,再对其进行反转 Assign next addresses to addresses[], and reverse it by k
int count = 0;
// 从头节点的地址开始拷贝,到空地址(null)为止
for (int j = head; j != -1; j = node[j].next){
addresses[count++] = j;
}
// 每K个地址进行一次反转
for (int j = 0; j < count - count % K; j += K){
reverse(addresses + j, addresses + j + K);
}
// 输出结果
for (int i = 0; i < count; i++){
// 用printf()将地址的打印格式统一为六位数(除null外)
if (i == count - 1){
// 最后一个节点的下一节点地址为空,不可访问(segmentation fault)
printf("%05d %d -1\n", addresses[i], node[addresses[i]].value);
}
else{
printf("%05d %d %05d\n", addresses[i], node[addresses[i]].value, addresses[i+1]);
}
}