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 (<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
链表排序,注意链表长度可能为0,否则pat最后一个测试点过不去。
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef struct node{
int addr,next,v;
}node;
node l[100005];
bool cmp(node &n1,node &n2){
return n1.v<n2.v;
}
int main(){
int n,head;
scanf("%d %d",&n,&head);
for(int i=0;i<n;i++){
int addr;
scanf("%d",&addr);
scanf("%d %d",&l[addr].v,&l[addr].next);
l[addr].addr=addr;
}
vector<node> li;
for(int i=head;i!=-1;i=l[i].next)
li.push_back(l[i]);
if(li.size()==0){
printf("%d %d\n",li.size(),-1);
return 0;
}
sort(li.begin(),li.end(),cmp);
printf("%d %05d\n",li.size(),li[0].addr);
int i=0;
for(;i<li.size()-1;i++){
printf("%05d %d %05d\n",li[i].addr,li[i].v,li[i+1].addr);
}
printf("%05d %d %d\n",li[i].addr,li[i].v,-1);
return 0;
}
本文详细解析了链表排序算法的实现过程,通过输入链表节点的地址、键值和下一个节点的地址,将链表按照键值进行升序排序。文章提供了完整的C++代码示例,展示了如何读取链表数据、排序链表节点以及输出排序后的链表。
620

被折叠的 条评论
为什么被折叠?



