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 aNext 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 12345Sample Output:
5 12345 12345 -1 00001 00001 0 11111 11111 100 22222 22222 1000 33333 33333 100000 -1
要求给一个链表排序,其中数值都是唯一的。这里用sort函数对结构体就能完成排序的问题,然后依次输出当前点地址,当前点的数值和当前点的下一个点的地址。不过要注意的是给出的点不一定全部在这个链表中,要先从头节点开始先遍历一遍链表,把节点信息保存好再进行排序。还要注意的是链表是空的情况。
代码:
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
struct node
{
int addr;
int key;
node(int a,int k):addr(a),key(k){}
};
bool cmp(const node &n1,const node &n2)
{
return n1.key<n2.key;
}
int main()
{
int n,first;
scanf("%d %d",&n,&first);
int next[100001];
int keys[100001];
memset(next,-1,100001);
vector<node>list;
for(int i=0;i<n;i++)
{
int from,key,to;
scanf("%d %d %d",&from,&key,&to);
if(from>=0&&from<100000)
{
next[from]=to;
keys[from]=key;
}
}
int cur=first;
while(cur>=0)
{
list.push_back(node(cur,keys[cur]));
cur=next[cur];
}
if(list.empty())
{
if(first==-1)
printf("0 -1\n");
else
printf("0 %5d\n",first);
return 0;
}
sort(list.begin(),list.end(),cmp);
printf("%d %05d\n",list.size(),list[0].addr);
for(int i=0;i<list.size();i++)
{
if(i<list.size()-1) printf("%05d %d %05d\n",list[i].addr,list[i].key,list[i+1].addr);
else printf("%05d %d -1\n",list[i].addr,list[i].key);
}
}