L2-022 重排链表

题解

类似于数组模拟链表,开一个1e5大小的数组,存储当前元素节点和下一个节点标号。
从链表头开始将链表压缩在一起并保留相对位置关系存入vec,再根据题目要求首尾交替的存入ans数组。
最后根据ans的相对位置关系,根据题目要求模拟链表的格式输出。注意遍历ans时不能用n来代表范围,因为有多余节点。

AC代码

#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int N = 1e5 + 10;

struct node
{
	int val, nxt;
}ls[N];
int main()
{
#ifdef LOCAL
	//freopen("C:/input.txt", "r", stdin);
#endif
	int h, n;
	cin >> h >> n;
	for (int i = 0; i < n; ++i)
	{
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		ls[a] = { b, c };
	}
	vector<node> vec, ans;
	for (int i = h; ~i; i = ls[i].nxt)
		vec.push_back({ ls[i].val, i });
	int l = 0, r = vec.size() - 1; //3号样例有多余节点不能为n!!!
	while (l <= r)
	{
		ans.push_back(vec[r--]);
		if (l <= r)
			ans.push_back(vec[l++]);
	}
	for (int i = 0; i < vec.size(); ++i)
	{
		printf("%05d %d ", ans[i].nxt, ans[i].val);
		if (i != vec.size() - 1)
			printf("%05d\n", ans[i + 1].nxt);
		else
			printf("-1\n");
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值