PAT 1052. Linked List Sorting
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.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive N (< 105) 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.
Output Specification:
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.
Sample Input:
5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345
Sample Output:
5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
分析
这题首先从给的head address开始遍历,直到为-1,把遍历中的节点储存起来,这是因为并不是所有给的节点都在list中,在list中的是head address到-1之间的所有节点。然后按节点的data排序。输出时,第一行输出节点个数,注意是list中节点的个数和头结点的id,然后从第二行开始除了最后一行每行输出该节点的id,该节点的data,下一个节点的id。最一行输出节点的id,节点的data,-1。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int data,id,next;
};
bool cmp(const node& n1,const node& n2){
return n1.data<n2.data;
}
int main(){
int n,s,id;
cin>>n>>s;
vector<node> vi(100000),res;
for(int i=0;i<n;i++){
cin>>id;
cin>>vi[id].data>>vi[id].next;
vi[id].id=id;
}
while(s!=-1){
res.push_back(vi[s]);
s=vi[s].next;
}
sort(res.begin(),res.end(),cmp);
if(res.size()==0){
printf("%d %d",res.size(),-1);
return 0;
}
printf("%d %05d\n",res.size(),res[0].id);
int i;
for(i=0;i<res.size()-1;i++)
printf("%05d %d %05d\n",res[i].id,res[i].data,res[i+1].id);
printf("%05d %d %d\n",res[i].id,res[i].data,-1);
return 0;
}