PAT甲级刷题记录——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 keyand 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 (<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 Addressis the address of the node in memory, Keyis an integer in [?105? ,105?? ], and Nextis 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

思路 这题和【1074 Reversing Linked List (25分)】很像,不过1074是让你反转链表,而本题是让你对链表的data域从小到大进行排序。做法还是一样的,先把题目给的数据全部读入到Node数组里,然后再从头结点开始走,把有效结点依次放到List数组里,再用cmp函数按data的值从小到大给List数组排个序,此时,我们的List数组的address和data都已经满足题目要求了,因此,只要从后往前改List数组每个元素的next域即可(前一个的next域是后一个的address)。
这题和1074不同的地方在于,这题可能出现全是无效结点的情况,所以此时要特判输出“0 -1”。
【PAT甲级刷题记录——1052 Linked List Sorting (25分)】于是我得出了一个结论:
如果这类链表的题目有那么一两个测试点WA,多半以下两种情况:
  • 把N当成是有效结点的个数了。这是我在做1074的时候犯的错误,事实上,题目给出的N个结点不一定全在链表上;
  • 有可能题目存在所有结点都是无效结点的情况(这种情况好像1074不存在??那题我没有特判所有结点都是无效结点也AC了)。
代码
#include #include #include #include #include using namespace std; const int maxn = 100001; struct node{ int address; int data; int next; }Node[maxn], List[maxn]; bool cmp(node a, node b){ return a.data=0){ for(int i=index-2; i>=0; i--){ List[i].next = List[i+1].address; } } printf("%d %05d\n", index, List[0].address); for(int i=0; i

    推荐阅读