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:
1 | 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:
1 | 5 00001 |
Sample Output:
1 | 5 12345 |
作者: CHEN, Yue
单位: 浙江大学
时间限制: 400 ms
内存限制: 64 MB
代码长度限制: 16 KB
题目大意
给出一个链表,要求对链表进行排序
分析
这题主要坑在于有些点不在链表中。因此用一个map<int,node>
存放所有的结点,key为addr。然后从头结点开始,遍历,找出链表中的结点加入vector<node>
。然后只需调用sort函数排序即可。
注意处理head为-1的情况,直接输出”0 -1”,否则会有一个测试点段错误。
代码
1 |
|