题目地址:
https://pintia.cn/problem-sets/994805342720868352/problems/994805425780670464
思路是先结构体开散列,然后把链表放到vector里,再进行排序
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
//new and delete
//A1052 Linked List Sorting
using namespace std;
const int MaxN = 100010;
struct Node {
int addr=-1;
int Key = -100010;
int Next = -1;
}List[MaxN];
bool cmp(Node a,Node b) {
return a.Key < b.Key;
}
int main() {
int N;
int Head;
vector<Node> List1; //输出的结构体vector
cin >> N >> Head;
if (Head == -1) //如果没有节点
{
printf("0 -1\n");
return 0;
}
for (int i = 0; i < N; i++) {
int addr, key, next;
cin >> addr >> key >> next;
List[addr].addr = addr;
List[addr].Key = key;
List[addr].Next = next;
}
for (int i = Head; i != -1;) {
List1.push_back(List[i]);
i = List[i].Next;
}
N = List1.size();
sort(&List1[0], &List1[0]+N, cmp);
//输出
printf("%d %05d\n", N, List1[0].addr);
for (int i = 0; i < N; i++) {
printf("%05d %d ", List1[i].addr, List1[i].Key);
if (i == N - 1) {
List1[i].Next = -1;
printf("-1\n");
}
else
{
List1[i].Next = List1[i + 1].addr;
printf("%05d\n", List1[i].Next);
}
}
return 0;
}