技巧:创建一个空的头指针,方便翻转后的连接原链表的操作
C++ 代码
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_N = 100010;
int ne[MAX_N];
int node[MAX_N];
int Reverse(int head, int k) {
int rear = ne[head]; //反转后的最后一个结点
int pL = ne[head]; //从头结点的下个结点开始翻转
int pR = ne[pL];
for (int i = 0; i < k - 1; i++) { //k个节点翻转k-1次
int t = ne[pR];
ne[pR] = pL;
pL = pR;
pR = t;
}
//将反转后的链表与未反转链表连起来
ne[head] = pL;
ne[rear] = pR;
return rear; //返回翻转链表的最后一个节点
}
int main() {
int head, p;
int h, n, k;
cin >> h >> n >> k;
//创建空的头指针
head = MAX_N - 1;
ne[head] = h;
for (int i = 0; i < n; i++) {
int addr, data, nextAddr;
cin >> addr >> data >> nextAddr;
node[addr] = data;
ne[addr] = nextAddr;
}
//统计有效链表的长度
p = head;
int cnt = 0;
while (p != -1) {
p = ne[p];
cnt++;
}
n = cnt;
//翻转链表
p = head;
for (int i = 0; i + k < n; i += k) p = Reverse(p, k);
//打印链表
p = ne[head];
while (p != -1) {
printf("%05d %d ", p, node[p]);
if (ne[p] != -1) printf("%05d\n", ne[p]);
else puts("-1");
p = ne[p];
}
return 0;
}