PAT A 1052 Linked List Sorting (25分)

一、思路

定义结构体node{addr, data, next};
为避免出现给定结点集合中,有非链表成员的情况,先将结点按下标存储,再按照指针遍历,同时保存链表中的结点,并对结点排序,输出;

二、代码

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct
{
    int addr, data, next;
}node;
int main()
{
    vector<node> l(100000), ans;
    int N, head;
    node temp;
    scanf("%d %d", &N, &head);
    for( int i = 0, addr; i < N; ++i )
    {
        scanf("%d %d %d", &temp.addr, &temp.data, &temp.next);
        l[ temp.addr ] = temp;
    }
    for( int addr = head; addr != -1; addr = l[addr].next )
        ans.push_back(l[addr]);
    sort( ans.begin(), ans.end(), [](node a, node b){ return a.data < b.data; } );
    printf("%d", ans.size());
    for( int i = 0; i < ans.size(); ++i )
        printf(" %05d\n%05d %d", ans[i].addr, ans[i].addr, ans[i].data);
    printf(" -1");
}

发布了152 篇原创文章 · 获赞 144 · 访问量 9214

猜你喜欢

转载自blog.csdn.net/qq_43749739/article/details/103944383