A1052 Linked List Sorting (25 分| 链表,附详细注释,逻辑分析)

写在前面

  • 思路分析
    • 给出1个链表,将链表排序,然后把链表上的结点按照data值的从小到大顺序输出
    • 实现分析:
      • 建立结构体数组,按照从首地址开始的顺序(直到-1)遍历整个链表,将在链表中结点的flag标记为true,并且统计cnt(有效结点的个数)。
        • 因为有的结点根本不不在链表中
      • 然后将链表进行排序,如果flag == false就把他们移动到后面(即: reuturn a.flag > b.flag) ,最后只输出
        前cnt个链表的信息
  • 题目基础,20分钟a题

测试用例

  • input:
    5 00001
    11111 100 -1
    00001 0 22222
    33333 100000 11111
    12345 -1 33333
    22222 1000 12345
    output:
    5 12345
    12345 -1 00001
    00001 0 11111
    11111 100 22222
    22222 1000 33333
    33333 100000 -1
    

ac代码

  • #include <iostream>
    #include <algorithm>
    using namespace std;
    struct NODE
    {
        int address, key, next;
        bool flag;
    } node[100000];
    int cmp1(NODE a, NODE b)
    {
        return !a.flag || !b.flag ? a.flag > b.flag : a.key < b.key;
    }
    int main()
    {
        int n, cnt = 0, s, a, b, c;
        scanf("%d%d", &n, &s);
        for(int i = 0; i < n; i++)
        {
            scanf("%d%d%d", &a, &b, &c);
            node[a] = {a, b, c, false};
        }
        for(int i = s; i != -1; i = node[i].next)
        {
            node[i].flag = true;
            cnt++;
        }
        if(cnt == 0)
            printf("0 -1");
        else
        {
            sort(node, node + 100000, cmp1);
            printf("%d %05d\n", cnt, node[0].address);
            for(int i = 0; i < cnt; i++)
            {
                printf("%05d %d ", node[i].address, node[i].key);
                if(i != cnt - 1)
                    printf("%05d\n", node[i + 1].address);
                else
                    printf("-1\n");
            }
        }
        return 0;
    }
    
发布了328 篇原创文章 · 获赞 107 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/qq_24452475/article/details/100619849