【PAT】A-1052 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 (<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

题意

给出一个链表,将它按从小到大排序输出。

思路

读取数据预处理后,地址有序存放在一维数组sorted中,将其按值的大小排序后,当前结点的下一个结点的地址就是sorted数组中的下一个元素(最后一个结点的next为-1)

代码

#include 
#include 
using namespace std;
#define MAX 100000
int value[MAX], sorted[MAX], cnt = 0;
int cmp(int a, int b){
    return value[a] < value[b];
}
int main() {
    int N, S, next[MAX];
    scanf("%d %d",&N, &S);
    for(int i = 0, address; i < N; i++){
        scanf("%d", &address);
        scanf("%d", &value[address]);
        scanf("%d", &next[address]);
    }
    for(int x = S; x != -1; x = next[x]){
        sorted[cnt++] = x;
    }
    
    if(cnt == 0){
        printf("0 -1");
        return 0;
    }
    
    sort(sorted, sorted + cnt, cmp);
    printf("%d %05d\n", cnt, sorted[0]);
    for(int i = 0, t, l = cnt - 1; i < l; i++){
        t = sorted[i];
        printf("%05d %d %05d\n", t, value[t], sorted[i + 1]);
    }
    printf("%05d %d -1\n", sorted[cnt - 1], value[sorted[cnt - 1]]);
    return 0;
}

你可能感兴趣的:(PAT)