找出一条有效的链表按value排序输出,输入没有环
题目描述
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.
输入描述:
Each input file contains one test case. For each case, the first line contains a positive N (5) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [-105, 105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.
输出描述:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
输入例子:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
输出例子:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
#include<bits/stdc++.h>
#include <iostream>
#include <map>
#include <string>
#include<vector>
#include<stack>
using namespace std;
struct node{
int ad;
int va;
int nx;
bool flag;
};
bool cmp(node a,node b)
{
if(a.flag==false||b.flag==false)
{
return a.flag>b.flag;
}
else
return a.va<b.va;
}
node a[100005];
int main()
{
int n,star;
cin>>n>>star;
int add,val,nxtnum;
for(int i=0;i<100000;i++)
{
a[i].flag=false;
}
for(int i=0;i<n;i++)
{
cin>>add;
cin>>a[add].va>>a[add].nx;
a[add].ad=add;
}
int cnt=0,s=star;
while(s!=-1)
{
a[s].flag=true;
cnt++;
s=a[s].nx;
}
if(cnt!=0)
{
sort(a,a+100005,cmp);
s=a[0].ad;
printf("%d %05d\n",cnt,s);
for(int i=0;i<cnt;i++)
{
if(i<cnt-1)
printf("%05d %d %05d\n",a[i].ad,a[i].va,a[i+1].ad);
else
printf("%05d %d -1\n",a[i].ad,a[i].va);
}
}
else cout<<0<<" "<<-1<<endl;
return 0;
}