PAT甲级1052 Linked List Sorting (25分)|C++实现

一、题目描述

原题链接
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:

在这里插入图片描述

​​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

二、解题思路

一道比较简单的链表题,我们可以通过静态链表实现,将每个节点建立为结构体,包括地址、数据和下一个元素的地址。用while循环遍历一遍链表,将节点存入vector<Node> list中,随后用sort函数进行排序,随后进行输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 100010;
struct Node
{
    int add, key, next;
}node[maxn];
vector<Node> list;
bool cmp(Node a, Node b)
{return a.key < b.key;}
int main()
{
    int N, first, tmp;
    scanf("%d%d", &N, &first);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &tmp);
        scanf("%d%d", &node[tmp].key, &node[tmp].next);
        node[tmp].add = tmp;
    }
    tmp = first;
    while(tmp != -1)
    {
        list.push_back(node[tmp]);
        tmp = node[tmp].next;
    }
    sort(list.begin(), list.end(), cmp);
    int sze = list.size();
    if(sze == 0)
    {
        printf("0 -1");
        return 0;
    }
    printf("%d %05d\n", sze, list[0].add);
    for(int i=0; i<sze-1; i++)
    {
        printf("%05d %d %05d\n", list[i].add, list[i].key, list[i+1].add);
    }
    printf("%05d %d -1", list[sze-1].add, list[sze-1].key);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值