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;
}
相关推荐
拾忆,想起8 小时前
Dubbo超时问题排查与调优指南:从根因到解决方案
服务器·开发语言·网络·微服务·架构·php·dubbo
7ioik9 小时前
什么是线程池?线程池的作用?线程池的四种创建方法?
java·开发语言·spring
晨非辰9 小时前
数据结构排序系列指南:从O(n²)到O(n),计数排序如何实现线性时间复杂度
运维·数据结构·c++·人工智能·后端·深度学习·排序算法
小曹要微笑9 小时前
STM32H7系列全面解析:嵌入式性能的巅峰之作
c语言·stm32·单片机·嵌入式硬件·算法
寻星探路9 小时前
JavaSE重点总结后篇
java·开发语言·算法
Charles_go10 小时前
C#中级8、什么是缓存
开发语言·缓存·c#
残影飞雪10 小时前
Jetson版本下Pytorch和torchvision
c++
松涛和鸣11 小时前
14、C 语言进阶:函数指针、typedef、二级指针、const 指针
c语言·开发语言·算法·排序算法·学习方法
yagamiraito_13 小时前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
星释13 小时前
Rust 练习册 57:阿特巴什密码与字符映射技术
服务器·算法·rust