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;
}
相关推荐
张张123y2 小时前
DSH 插件调试避坑:client.js 设置面板、热重载与高频报错排查表
开发语言·javascript·人工智能·开源·ecmascript·后端开发·ai agent
Navigator_Z3 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack4 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH4 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶5 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
FRing035 小时前
vue2干货总结7(自定义指令、插槽、单页应用程序、路由的使用(VueRouter))
开发语言·前端·vue.js·vue2
雪落漂泊5 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
波力海苔夹心脆6756 小时前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
不会算法的笨小孩7 小时前
异常的使用以及会出现的问题
开发语言·c++·c++11·异常