给一个链表,然后按链表里面的数据排序,重新排成一个链表。
注意给的数据里面有掺杂的无用节点,不能直接排序。
所以应该遍历一遍链表之后标记出有用节点再排序。
#include<cstdio>
#include<map>
#include <algorithm>
using namespace std;
const int N = 100010;
struct Node{
int address;
int v;
int next;
bool flag = false;
}node[N];
bool cmp(Node a,Node b){
if(a.flag==false)
return false;
else if(b.flag==false)
return true;
else{
return a.v<b.v;
}
}
int main(){
int n,firstadd;
scanf("%d %d",&n,&firstadd);
int tempadd;
for(int i = 0;i < n;i++){
scanf("%d",&tempadd);
scanf("%d %d",&node[tempadd].v,&node[tempadd].next);
node[tempadd].address = tempadd;
}
int count=0;
tempadd = firstadd;
while(tempadd!=-1){
node[tempadd].flag = true;
tempadd = node[tempadd].next;
count++;
}
if(count==0){
printf("0 -1");
}else{
//从小往大排序
sort(node,node+N,cmp);
firstadd = node[0].address;
printf("%d %05d
",count,firstadd);
for(int i = 0;i<count;i++){
printf("%05d %d",node[i].address,node[i].v);
if(i != count-1){
printf(" %05d
",node[i+1].address);
}else{
printf(" -1
");
}
}
}
return 0;
}
代码二:map映射地址
#include<cstdio>
#include<map>
using namespace std;
const int N = 100010;
map<int,int> mp;
struct Node{
int address;
int v;
int next;
}node[N];
int main(){
int n,firstadd;
scanf("%d %d",&n,&firstadd);
int tempadd;
for(int i = 0;i < n;i++){
scanf("%d",&tempadd);
scanf("%d %d",&node[tempadd].v,&node[tempadd].next);
node[tempadd].address = tempadd;
}
tempadd = firstadd;
while(tempadd!=-1){//遍历
mp.insert(make_pair(node[tempadd].v,node[tempadd].address));
tempadd = node[tempadd].next;
}
//mp从小往大排序
if(mp.size()==0){
printf("0 -1");
}else{
int count = 0;
map<int,int>::iterator it = mp.begin();
firstadd = it->second;
printf("%d %05d
",mp.size(),firstadd);
while(it!=mp.end()){
printf("%05d %d",it->second,it->first);
it++;
count++;
if(count != mp.size()){
printf(" %05d
",it->second);
}else{
printf(" -1
");
}
}
}
return 0;
}