题目

21分的解法:
直接按照key的大小排序后,改变next指针
点击查看代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{
int key;
string next;
};
bool cmp(const pair<string,Node> &p1,const pair<string,Node> &p2){
return p1.second.key<p2.second.key;
}
int main(){
int n;
string begin;
cin>>n>>begin;
vector<pair<string,Node>> v(n);
for(int i=0;i<n;i++){
string addr;
Node node;
cin>>addr>>node.key>>node.next;
v[i]={addr,node};
}
sort(v.begin(),v.end(),cmp);
for(int i =0;i<n-1;i++){
v[i].second.next = v[i+1].first;
}
v[n-1].second.next = "-1";
cout<<n<<" "<<v[0].first<<endl;
for(int i =0;i<n;i++){
printf("%s %d %s\n",v[i].first.c_str(),v[i].second.key,v[i].second.next.c_str());
}
return 0;
}
满分解法
考虑特殊情况,可能所给的结点不在链表中
点击查看代码
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
struct Node {
int key;
string next;
};
// 比较函数,用于排序
bool cmp(const pair<string, Node>& a, const pair<string, Node>& b) {
return a.second.key < b.second.key;
}
int main() {
int N;
string head;
unordered_map<string, Node> nodeMap; // 暂存输入节点
vector<pair<string, Node>> nodes; // 存储有效的链表节点
// 输入 N 和 head 地址
cin >> N >> head;
// 读取所有节点
for (int i = 0; i < N; i++) {
string addr, next;
int key;
cin >> addr >> key >> next;
nodeMap[addr] = {key, next};
}
// 遍历链表,提取有效节点。只有从 begin 开始,沿着 next 能走到的节点才是有效的链表节点,其他的都是无效节点。
string cur = head;
while (cur != "-1" && nodeMap.find(cur) != nodeMap.end()) {
nodes.push_back({cur, nodeMap[cur]});
cur = nodeMap[cur].next;
}
// 计算有效节点个数
int validCount = nodes.size();
if (validCount == 0) {
cout << "0 -1" << endl; // 没有有效节点,输出 0 -1,比如输入的起始结点为空
return 0;
}
// 按 key 排序
sort(nodes.begin(), nodes.end(), cmp);
// 更新 next 指针
for (int i = 0; i < validCount - 1; i++) {
nodes[i].second.next = nodes[i + 1].first;
}
nodes[validCount - 1].second.next = "-1"; // 最后一个节点 next 设为 -1
// 输出结果
cout << validCount << " " << nodes[0].first << endl;
for (int i = 0; i < validCount; i++) {
cout << nodes[i].first << " " << nodes[i].second.key << " " << nodes[i].second.next << endl;
}
return 0;
}
浙公网安备 33010602011771号