1052 Linked List Sorting (25分)链表排序(不需要模拟链表操作)

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805425780670464

题意

给出链表每个结点信息 address key next
按key排序再输出

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

坑点

  1. 不需要模拟链表操作,构造好链表后,顺序遍历一次存入数组,直接sort大法
  2. 有些结点不在链表中,需要抛弃,使得输出总结点数不为n
  3. 头结点可能为-1
/***************************
        Hello World!
***************************/
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

int n;
int head;

struct node{
    int key;
    int ne;//5位
}List[100005],a[100005];

bool cmp(node x,node y) { return x.key<y.key; }

int main()
{
    scanf("%d%d",&n,&head);
    for(int i=1;i<=n;i++) {
        int add,key,ne;
        scanf("%d%d%d",&add,&key,&ne);
        List[add].key=key;
        List[add].ne=ne;
    }
    
    //特判啊啊啊啊啊啊啊
    if(head==-1){
        printf("0 -1\n");
        return 0;
    }
    int p=head,j=-1;
    while(p!=-1)
    {
        ++j;
        a[j].key=List[p].key;
        a[j].ne=p;
        p=List[p].ne;
    }
    //有的结点不在链表中
    sort(a,a+j+1,cmp);
    printf("%d %05d\n",j+1,a[0].ne);
    for(int i=0;i<=j;i++)
    {
        printf("%05d %d ",a[i].ne,a[i].key);
        if(i!=j) printf("%05d\n",a[i+1].ne);
        else printf("-1\n");
    }
    return 0;
}
/***************************
        The end!
***************************/

ps:第一次用markdown写博客

posted @ 2020-08-01 00:30  liuyongliu  阅读(126)  评论(0编辑  收藏  举报