PAT(A)1052 Linked List Sorting (25point(s))

在这里插入图片描述

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

思路:
链表排序,但真正意义上就是把内部进行值得排序。
注意输出格式。
代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>

using namespace std;

#define endl '\n'

typedef long long ll;

struct node {
    int address;
    int key;
    int next;
    int f = 0;
}p[1000005], ans[1000005];

bool cmp(node a, node b)
{
    return a.key < b.key;
}

int main()
{
    int n, start;

    cin >> n >> start;

    for (int i = 0; i < n; ++i)
    {
        int add;
        cin >> add;
        p[add].address = add;
        cin >> p[add].key >> p[add].next;
        p[add].f = 1;
    }

    int num = 0;

    while (1)
    {
        if (p[start].f == 0)
            break;
        ans[num++] = p[start];
        start = p[start].next;
        if (start == -1)
            break;
    }

    if (num == 0)
    {
        printf("0 -1\n");
        return 0;
    }


    sort(ans, ans + num, cmp);

    printf("%d %05d\n", num, ans[0].address);

    for (int i = 0; i < num - 1; ++i)
    {
        printf("%05d %d %05d\n", ans[i].address, ans[i].key, ans[i + 1].address);
    }


    printf("%05d %d -1\n", ans[num - 1].address, ans[num - 1].key);

    return 0;
}

发布了161 篇原创文章 · 获赞 7 · 访问量 7082

猜你喜欢

转载自blog.csdn.net/weixin_43778744/article/details/104142558