当前位置: 代码迷 >> 综合 >> [PAT A1052]Linked List Sorting
  详细解决方案

[PAT A1052]Linked List Sorting

热度:17   发布时间:2023-12-15 06:11:17.0

[PAT A1052]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.

输入格式

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.

输出格式

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.

输入样例

5 00001

11111 100 -1

00001 0 22222

33333 100000 11111

12345 -1 33333

22222 1000 12345

输出样例

5 12345

12345 -1 00001

00001 0 11111

11111 100 22222

22222 1000 33333

33333 100000 -1

解析

  1. 题目大意是:输入n个结点,对于每个结点,输入它的地址、存储数和下一个结点的地址,然后对于链表中每一个元素,按照存储数从小到大排序,并将他们输出
  2. 注意并不是所有的结点都是合法的,这里使用key值判断这个点在不在链表上,即该点合不合法
  3. 如果链表为空,那就要输出0 -1,这个地方需要处理
  4. #include<iostream>
    #include<algorithm>
    using namespace std;
    struct node {int addr, data, next;bool key = false; //用于判断该点在不在链表上
    };
    node nodes[100010];
    bool cmp(node n1, node n2) {if (n1.key&&n2.key)return n1.data < n2.data; //如果两个点都有效,那么按data升序排列else return n1.key > n2.key; //如果两个点中至少一个无效,那么把有效结点放在前面
    }
    int main()
    {int n, start, cnt = 0;scanf("%d%d", &n, &start);for (int i = 0; i < n; i++) {int addr, data, next;scanf("%d%d%d", &addr, &data, &next);nodes[addr].addr = addr;nodes[addr].data = data;nodes[addr].next = next;}while (start != -1) {nodes[start].key = true;start = nodes[start].next;cnt++;} //记录有效结点个数sort(nodes, nodes + 100000, cmp);if (cnt == 0) printf("0 -1");else {printf("%d %05d\n", cnt, nodes[0].addr);for (int i = 0; i < cnt - 1; i++) printf("%05d %d %05d\n", nodes[i].addr, nodes[i].data, nodes[i + 1].addr);printf("%05d %d -1", nodes[cnt - 1].addr, nodes[cnt - 1].data);}return 0;
    }

     

  相关解决方案