1052 Linked List Sorting (25 分)

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 (<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 [−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:

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.题目中给出的节点虽然在memory(内存)中,但是不一定在链表上,因此需要根据头结点head进行一次遍历收集链表上的节点,然后进行排序。
2.有可能所有的节点都不在一个链表上,此时链表的size是0,头节点是-1(代表NULL)。
注:注意点1在第一次提交时已经想到,但是注意点2有点隐蔽,在提交时报段错误,自然想到溢出或越界,那只能是最后输出序列时默认节点数大于等于1导致的越界,修改这个错误之后,错误提示变为答案错误,于是开始思考头结点错误,此时头结点参考的是head,最后看博客[1]发现此时的头结点是-1。与其说这个测试点隐蔽,比如说这个测试点诡异,因为已经给出了头结点的地址,说明内存中头结点是存在的,至少在访问的时候,链表能收录一个节点,即头结点head,并且题目也没有明确说链表中节点个数为0不能称为为链表,这便是我认为这个诡异的理由。其实发现PAT中有很多这种至少现在无法理解测试点,或许未读懂题意所致,或许编程题就应该这样严谨地考虑,反正做一题记住一题的刁钻测试点~~
博客[1]发现sort的cmp函数的一个新视角,其实sort本质是排序,我们也可以用它来控制元素的移动,以设定条件,通过条件的真假,间接控制元素的大小关系,从而调节元素间在排序过程中的移动。这个提这一点,主要因为之前做题一直思想僵化的将sort的cmp函数针对的是整个指定序列的排序,其实这个在cmp函数里面通过设定flag参数实现对指定序列中符合条件的元素进行排序,对这个现象做一点记录,日后再博客是可以打破思维僵化~~~。

#include 
#include 
#include 
#include 
using namespace std;
map val_ad,ad_val,ad_next;
vector val;
int main(){
    int n,head;
    cin>>n>>head;
    for(int i=0;i>a>>b>>c;
        val_ad[b]=a;
        ad_val[a]=b;
        ad_next[a]=c;
    }
    for(int i=head;i!=-1;i=ad_next[i]){
        val.push_back(ad_val[i]);
    }
    sort(val.begin(), val.end());
    cout<

  1. https://www.liuchuo.net/archives/2116 ↩ ↩

你可能感兴趣的:(1052 Linked List Sorting (25 分))