码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1052. Linked List Sorting

时间:2015-02-25 09:06:58      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:利用vector是一个很好的方法,另外一点需要注意的就是全部无效的节点。一定要进行特殊输出
技术分享
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <vector>
 5 using namespace std;
 6 const int MAX = 100010;
 7 struct Info
 8 {
 9     int address;
10     int data;
11     int next;
12 }; 
13 bool cmp(Info A,Info B)
14 {
15 
16    return A.data<B.data;
17 }
18 
19 
20 int main(int argc, char *argv[])
21 {
22     int N,start;
23     scanf("%d%d",&N,&start);
24     vector<Info>in(MAX);
25     vector<Info>out;
26     for(int i=0;i<N;i++)
27     {
28         Info node;
29         scanf("%d%d%d",&node.address,&node.data,&node.next);
30         in[node.address]=node;
31     }
32     int pt=start;
33     while(pt!=-1)
34     {
35         out.push_back(in[pt]);
36         pt=in[pt].next;
37     }
38     sort(out.begin(),out.end(),cmp);
39     if(out.size()!=0)
40       printf("%d %05d\n",out.size(),out[0].address);
41     else
42       printf("%d -1\n",out.size());
43     for(int i=0;i<out.size();i++)
44     {
45         if(i==out.size()-1)
46           printf("%05d %d -1\n",out[i].address,out[i].data);
47         else
48              printf("%05d %d %05d\n",out[i].address,out[i].data,out[i+1].address);
49     }
50     
51     return 0;
52 }
View Code

 

PAT1052. Linked List Sorting

标签:

原文地址:http://www.cnblogs.com/GoFly/p/4299127.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!