题目
![]()
解法1
点击查看代码
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
struct Node {
int data;
string next;
};
int main() {
string head;
int n, k;
cin >> head >> n >> k;
unordered_map<string, Node> map;
vector<string> negative, between, greater; // 三个类别的地址列表
// 读取链表数据
for (int i = 0; i < n; i++) {
string addr;
Node node;
cin >> addr >> node.data >> node.next;
map[addr] = node; // 存入哈希表
}
// 遍历原链表,将节点分类
string curr = head;
while (curr != "-1") {
int val = map[curr].data;
if (val < 0) {
negative.push_back(curr);
} else if (val <= k) {
between.push_back(curr);
} else {
greater.push_back(curr);
}
curr = map[curr].next; // 移动到下一个节点
}
// 重新组织链表顺序
vector<string> result;
result.insert(result.end(), negative.begin(), negative.end());
result.insert(result.end(), between.begin(), between.end());
result.insert(result.end(), greater.begin(), greater.end());
// 输出新链表
for (size_t i = 0; i < result.size(); i++) {
string addr = result[i];
string nextAddr = (i + 1 < result.size()) ? result[i + 1] : "-1";
printf("%s %d %s\n", addr.c_str(), map[addr].data, nextAddr.c_str());
}
return 0;
}