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;
}
相关推荐
地平线开发者1 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮1 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者2 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考2 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx5 小时前
CART决策树基本原理
算法·机器学习
Wect6 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱6 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
肆忆_9 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星13 小时前
虚函数表:C++ 多态背后的那个男人
c++
Gorway13 小时前
解析残差网络 (ResNet)
算法