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;
}
相关推荐
fqbqrr2 小时前
2606C++,C++构的多态
开发语言·c++
biter down2 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
小欣加油2 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
lqqjuly2 小时前
前沿算法深度解析(二)
人工智能·算法·机器学习
Yolo_TvT3 小时前
C++:析构函数
c++
徐小夕4 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github
threelab4 小时前
Three.js 物理模拟着色器 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
武器大师724 小时前
lv_binding_js 代码解读
开发语言·javascript·ecmascript
不知名的老吴4 小时前
线程的生命周期之线程“插队“
java·开发语言·python