PAT甲级——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
注意点
(1)题目给出的结点中可能有不在链表中的无效结点
(2)最后一个测试点测试的是首地址为 - 1,即为空链表的情况,此时只输出0 - 1
(3)输出时结点地址除 - 1外要有5位数字,不够则在高位补0 。所以地址 - 1要进行特判输出
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 int addr, val, next; 13 cin >> addr >> val >> next; 14 data.insert(make_pair(addr, make_pair(val, next))); 15 } 16 if (data.find(head) == data.end()) 17 { 18 cout << 0 << " " << -1 << endl; 19 return 0;//该链表为空 20 } 21 while (head != -1)//遍历一下数据,找到是链表中的数据 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 }