PAT A1052 Linked List Sorting 题解及注意事项

思路

因为输入数据中会有不在链表中的干扰存在,必须遍历一遍链表,标记所有在链表中的节点并记录个数cnt,然后最整个数组进行排序,将不在链表中的节点排到尾部,这样前cnt个有序节点即是排序后的节点,此后无需更改每个节点的next数值,只需输出 “L[i].add L[i].key L[i+1].add\n"即可,当输出到最后一个节点 特判输出“l[i].add L[i].key -1\n",如果cnt为0,特判输出“0 -1"

注意事项

  1. 注意给出的所有节点会存在不在链表中的节点,所以要过滤一遍使遍历的节点l[i].flag=1,同时cnt++统计链表中的节点个数,然后在cmp函数中将flag=0排在后边 然后输出前cnt个节点即可。

  2. 边界条件:如果cnt==0,不存在节点 特判输出“0 -1"

题解

#include<bits/stdc++.h>

using namespace std;

const int maxn = 100010;

struct Node {
    int add, key, next;
    int flag;
    Node() :flag(0) {}
};

bool cmp(Node a, Node b) {
    if (!(a.flag && b.flag))return a.flag > b.flag;
    return a.key < b.key;
}

Node l[maxn];

int main() {
    int n,p,m;
    cin >> n>>p;

    int a, b, c;
    for (int i = 0; i < n; ++i) {
        cin >> a >> b >> c;
        l[a].add = a;
        l[a].key = b;
        l[a].next = c;
    }
    int cnt = 0;
    while (p!=-1) {
        l[p].flag = 1;
        p = l[p].next;
        cnt++;
    }

    sort(l, l + maxn, cmp);

    printf("%d %05d\n", cnt, l[0].add);

    for (int i = 0; i < cnt; ++i) {
            if (i<cnt-1) {
                printf("%05d %d %05d\n", l[i].add, l[i].key, l[i + 1].add);
            }
            else  {
                printf("%05d %d -1\n", l[i].add, l[i].key);
            }
        }
    return 0;
}

 

posted @ 2020-09-21 20:27  tao10203  阅读(169)  评论(0)    收藏  举报