题目描述
链表由一系列的结构体组成,每个结构体中包含一个 Key 值和一个指向下一个结构体的 Next 指针。
现在,给出一个链表,请你按照 Key 值升序的顺序将链表重新排序。
补充
1、本题中可能不包含不在链表中的节点。
2、链表可能为空。(头节点地址为 −1−1)。
输入格式
第一行首先包含一个整数 N,表示总节点数量,然后包含链表头节点的地址。
接下来 N行,每行描述一个节点的信息,格式如下:
Address Key Next
其中 Address 是节点地址,Key 值是一个整数,Next 是下一个节点的地址。
地址都是 5位正整数,可能有前导 0。
保证各节点的 Key 值互不相同,且链表中不存在环形结构。
输出格式
第一行首先输出一个整数表示链表的总节点数量,然后输出排序后的链表头节点地址。
接下来若干行,从头节点开始,依次输出每个节点的信息,格式与输入相同。
数据范围
1≤N≤10^5
−10^5≤Key≤10^5
输入样例
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
输出样例
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
题解
#include<iostream>
#include<map>
#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
typedef struct d{
string a,b;
}dp;
int main(){
map<ll,dp> mp;
ll n,y,o;
string x,z,c;
dp h;
cin>>n>>c;
o=n;
while(n--){
cin>>x>>y>>z;
mp[y].a=x;
mp[y].b=z;
}
if(c=="-1"){
cout<<"0"<<" "<<"-1";
return 0;
}
map<ll,dp>::iterator it;
it=mp.begin();
h=it->second;
cout<<o<<" "<<h.a<<endl;
for(it=mp.begin();it!=mp.end();it++){
it++;
if(it==mp.end())
break;
it--;
h=it->second;
cout<<h.a<<" "<<it->first<<" ";
it++;
h=it->second;
cout<<h.a<<endl;
it--;
}
it--;
h=it->second;
cout<<h.a<<" "<<it->first<<" "<<n;
return 0;
}
这道题的难度中等,非常锻炼对哈希表的理解,谢谢大家。