题目
![]()
解法1
点击查看代码
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
int data;
string next;
};
int main() {
string begin;
int n, k;
cin >> begin >> n >> k;
unordered_map<string, Node> map;
for (int i = 0; i < n; i++) {
string addr, next;
int data;
cin >> addr >> data >> next;
map[addr] = {data, next};
}
vector<string> list;
string current = begin;
// 构建链表顺序
while (current != "-1") {
list.push_back(current);
current = map[current].next;
}
// 每 K 个节点反转一次
for (int i = 0; i + k <= list.size(); i += k) {
reverse(list.begin() + i, list.begin() + i + k);
}
// 输出结果
for (int i = 0; i < list.size(); i++) {
string addr = list[i];
string next = (i == list.size() - 1) ? "-1" : list[i + 1];
cout << addr << " " << map[addr].data << " " << next << endl;
}
return 0;
}