L2-022 重排链表

给定一个单链表 L1​→L2​→⋯→Ln−1​→Ln​,请编写程序将链表重新排列为 Ln​→L1​→Ln−1​→L2​→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤105)。结点的地址是5位非负整数,NULL地址用−1表示。

接下来有N行,每行格式为:

复制代码
Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为不超过105的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。

输出格式:

对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。

输入样例:

复制代码
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

输出样例:

复制代码
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1

#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <iomanip>
#include <algorithm>
using namespace std;
#define M 100000
//00100 6
//00000 4 99999
//00100 1 12309
//68237 6 - 1
//33218 3 00000
//99999 5 68237
//12309 2 33218
int val[M + 5] = { 0 }, nex[M + 5] = { 0 }, pre[M + 5] = { 0 };
int main() {
	int root, n, end;
	cin >> root >> n;
	for (int i = 0, a, b, c; i < n; i++) {
		cin >> a >> b >> c;
		val[a] = b;
		nex[a] = c;
		if (c != -1) pre[c] = a;
		if (c == -1) end = a;
	}
	while (1) {
		printf("%05d %d ", end, val[end]);
		if (root == end) {
			cout << "-1";
			return 0;
		}
		else printf("%05d\n", root);
		end = pre[end];
		printf("%05d %d ", root, val[root]);
		if (root == end) {
			cout << "-1";
			return 0;
		}
		else printf("%05d\n", end);
		root = nex[root];
	}
	
	return 0;
}
相关推荐
badhope2 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园3 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
C++ 老炮儿的技术栈3 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl3 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
Liu628883 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
IT猿手3 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队
AI科技星4 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
sunwenjian8864 小时前
Java进阶——IO 流
java·开发语言·python
波特率1152004 小时前
const关键字与函数的重载
开发语言·c++·函数重载
FL16238631294 小时前
[C#][winform]segment-anything分割万物部署onnx模型一键抠图演示
开发语言·c#