1052 Linked List Sorting(25 分)
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 (<10
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 [−10
5
,10
5
], 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
解题思路:
链表排序。
1.设置结构体数组表示链表节点,添加flag表示是否在一条链上。
2.从头节点开始遍历,同时计数在链表上的节点个数total。
3.排序。把在链表上的排在前面,其中再按照key升序排列。
4。输出时以结构体数组的先后代替next,要注意统计完total后,如果为零,要特判输出,而且输出时按照total,而不是原先的n。
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
struct Node{
int key,address,next;
bool flag;
Node(){
flag=false;
}
}node[maxn];
bool cmp(Node a,Node b){
if(a.flag !=b.flag )
return a.flag >b.flag ;
else
return a.key <b.key ;
}
int main(){
int n,total=0,head;
int ad;
scanf("%d %d",&n,&head);
for(int i=0;i<n;i++){
scanf("%d",&ad);
scanf("%d%d",&node[ad].key ,&node[ad].next );
node[ad].address =ad;
}
for(int i=head;i!=-1;i=node[i].next ){
node[i].flag =true;
total++;
}
if(total==0){
printf("0 -1\n");
}else{
sort(node,node+maxn,cmp);
printf("%d %05d\n",total,node[0].address );
for(int i=0;i<total-1;i++){
printf("%05d %d %05d\n",node[i].address ,node[i].key ,node[i+1].address );
}
printf("%05d %d -1",node[total-1].address ,node[total-1].key );
}
return 0;
}