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

PAT 1052. Linked List Sorting (25)

时间:2015-08-12 16:33:50      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

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

 此题需要注意的题目中所给的所有节点并非全部都在链表上,所以应该通过所给的start来去除不在链表上的节点

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <sstream>
 5 #include <algorithm>
 6 
 7 using namespace std;
 8 
 9 struct Node
10 {
11     int address;
12     int value;
13     int next;
14 };
15 
16 bool cmp(const Node& lhs, const Node& rhs)
17 {
18     return lhs.value < rhs.value;
19 }
20 
21 Node nodes[1000000];
22 
23 int main()
24 {
25     vector<Node> vec;
26     int NodeNum, start;
27     cin >> NodeNum >> start;
28 
29     for (int i = 0; i < NodeNum; i++)
30     {
31         Node tmp;
32         cin >> tmp.address >> tmp.value >> tmp.next;
33         nodes[tmp.address] = tmp;
34     }
35     int i = start;
36     while (i != -1)
37     {
38         vec.push_back(nodes[i]);
39         i = nodes[i].next;
40     }
41 
42     sort(vec.begin(), vec.end(), cmp);
43     cout << vec.size() << " ";
44     for (int i = 0; i < vec.size(); i++)
45     {
46         printf("%.05d\n", vec[i].address);
47         //cout << vec[i].address << endl;
48         //cout << vec[i].address << " " << vec[i].value << " ";
49         printf("%.05d %d ", vec[i].address, vec[i].value);
50     }
51     cout << -1;
52 }

 

PAT 1052. Linked List Sorting (25)

标签:

原文地址:http://www.cnblogs.com/jackwang822/p/4724412.html

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