PTA甲级考试真题练习52——1052 Linked List Sorting

题目

在这里插入图片描述

思路

先用线性数组将链表信息存储到数组中,每个数组中的信息包括下一个索引和值,然后在用vector模拟链表存储当前结点和值,按值排序后输出

坑点

测试点4会出现段错误的情况:忽略了输入结点全是无效结点的情况,应输出0 -1。

代码

#include <iostream>
#include<algorithm>
#include<vector>

using namespace std;
#define nmax 100005
#define inf 999999

int N[nmax];
int Key[nmax];
int n;
int first_ad;

struct Node
{
	int ad;
	int key;
};
vector<Node> vec;

bool cmp(const Node& a, const Node& b)
{
	return a.key < b.key;
}

int main()
{
	cin >> n >> first_ad;
	for (int i = 0; i < n; ++i) {
		int cur_ad, key, next_ad;
		cin >> cur_ad >> key >> next_ad;
		N[cur_ad] = next_ad;
		Key[cur_ad] = key;
	}
	int cur_ad = first_ad;
	while (cur_ad != -1) {
		Node node;
		node.ad = cur_ad;
		node.key = Key[cur_ad];
		vec.emplace_back(node);
		cur_ad = N[cur_ad];
	}
	sort(vec.begin(), vec.end(), cmp);
	if (vec.empty()) {
		printf("0 -1");
		return 0;
	}
	printf("%d %05d\n", n, vec[0].ad);
	for (int i = 0; i < vec.size()-1; ++i) {
		printf("%05d %d %05d\n", vec[i].ad, vec[i].key, vec[i + 1].ad);
	}
	printf("%05d %d -1", vec[vec.size() - 1].ad, vec[vec.size() - 1].key);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值