PAT1052 Linked List Sorting (25)

  • Post author:
  • Post category:其他


1052. Linked List Sorting (25)

时间限制
400 ms

内存限制
32000 kB

代码长度限制
16000 B

判题程序

Standard

作者
CHEN, Yue

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
这道题测试case太坑。。可能有节点不在链表上,还要注意链表可能为空
#include <stdio.h>
#include <algorithm>
using namespace std;
struct LList{
int address;
int key;
int next;
bool operator < (const LList &b) const
{
    return key < b.key;
}
};
LList a[100000], b[100000];
int main()
{
    int n, x;
    while(scanf("%d%d", &n, &x) != EOF)
    {
        int p, q, r;
        for(int i = 0; i < n; i++)
           {
              scanf("%d%d%d", &p, &q, &r);
              a[p].address = p;
              a[p].key = q;
              a[p].next = r;
           }
        if(x == -1)
        {
            printf("0 -1\n");
            continue;
        }
        int index = 0;
        while(x != -1)
        {
            b[index].address = a[x].address;
            b[index].key = a[x].key;
            b[index].next = a[x].next;
            x = a[x].next;
            ++index;
        }
        sort(b, b+index);
        printf("%d %05d\n", index, b[0].address);
        for(int i = 0; i < index-1; i++)
            printf("%05d %d %05d\n", b[i].address, b[i].key, b[i+1].address);
        printf("%05d %d -1\n", b[index-1].address, b[index-1].key);
    }
    return 0;
}



版权声明:本文为xtzmm1215原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。