PAT Grade --A1052 Linked List Sorting

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 (<) 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 −.

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 [−], 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

Note that the point
(1) the title given node might not invalid node list

(2) The last test was the first test point address - 1, is the empty list case, only this time the output of 0 - 1

(3) In addition to the output node address --1 it must have five digits, at high enough 0s. So Address - 1 special sentence to be output

 1 #include <iostream>
 2 #include <map>
 3 using namespace std;
 4 int main()
 5 {
 6     int N, head, maxV = -1000000;
 7     cin >> N >> head;
 8     map<int, int>value;
 9     map<int, pair<int, int>>data;
10     for (int i = 0; i < N; ++i)
11     {
12 is          int addr, Val, Next;
 13 is          CIN addr >> >> >> Val Next;
 14          data.insert (the make_pair (addr, the make_pair (Val, Next)));
 15      }
 16      IF (Data.Find (head) = = data.end ())
 . 17      {
 18 is          COUT << 0 << "  " << - . 1 << endl;
 . 19          return  0 ; // the list is empty 
20 is      }
 21 is      the while ! (head = - . 1 ) // iterate at the data, the data is found in the list of 
22      {
23         value.insert(make_pair(data[head].first, head));
24         head = data[head].second;
25     }
26     printf("%d %05d\n", value.size(), value.begin()->second);
27     for (auto ptr = value.begin(); ptr != value.end(); ++ptr)
28     {
29         if (ptr == value.begin())
30             printf("%05d %d ", ptr->second, ptr->first);
31         else
32             printf("%05d\n%05d %d ", ptr->second, ptr->second, ptr->first);
33     }
34     printf("%d\n", -1);
35     return 0;
36 }

 



Guess you like

Origin www.cnblogs.com/zzw1024/p/11281097.html
Recommended