PAT1052 Linked List Sorting (25)(25 分)
Posted pgzhang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT1052 Linked List Sorting (25)(25 分)相关的知识,希望对你有一定的参考价值。
1052 Linked List Sorting (25)(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 Nextpointer 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 (< 10^5^) 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 [-10^5^, 10^5^], 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
C++代码如下:
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 #include<queue> 5 using namespace std; 6 7 #define maxn 100010 8 9 struct Node { 10 int address; 11 int key; 12 int next; 13 bool flag = false; 14 }node[maxn]; 15 16 bool cmp(const Node &a, const Node &b) { 17 if (a.flag == false || b.flag == false) 18 return a.flag > b.flag; 19 else 20 return a.key < b.key; 21 } 22 23 int main() { 24 int n, add; 25 scanf("%d %d", &n, &add); 26 int begin; 27 for(int i=0;i<n;i++){ 28 scanf("%d", &begin); 29 scanf("%d %d", &node[begin].key, &node[begin].next); 30 node[begin].address = begin; 31 } 32 int cont=0,p=add; 33 while (p != -1) { 34 cont++; 35 node[p].flag = true; 36 p = node[p].next; 37 } 38 sort(node, node + maxn, cmp); 39 if (cont == 0) { 40 printf("0 -1 "); 41 return 0; 42 } 43 printf("%d %05d ", cont, node[0].address); 44 for (int i = 0; i < cont-1; i++) { 45 printf("%05d %d %05d ", node[i].address, node[i].key, node[i+1].address); 46 } 47 printf("%05d %d -1 ", node[cont - 1].address, node[cont - 1].key); 48 return 0; 49 }
以上是关于PAT1052 Linked List Sorting (25)(25 分)的主要内容,如果未能解决你的问题,请参考以下文章
PAT甲级1052 Linked List Sorting (25分)
PAT 1052. Linked List Sorting (25)
PAT1052 Linked List Sorting (25)(25 分)
PAT Advanced 1052 Linked List Sorting (25) [链表]