当前位置:网站首页>L2-022 重排链表 (25 分)(模拟链表)
L2-022 重排链表 (25 分)(模拟链表)
2022-08-08 16:50:00 【Here_SDUT】
给定一个单链表 L_1→L_2→⋯→L_{n−1}→L_n,请编写程序将链表重新排列为 L_n →L_1 →L_{n-1}→L_2→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。
输入格式: 每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤10^5)。结点的地址是5位非负整数,NULL地址用−1表示。
接下来有N行,每行格式为:
Address Data Next
其中Address是结点地址;Data是该结点保存的数据,为不超过10^5的正整数;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
分析:
用数组模拟链表就行,我的做法是先遍历一遍链表给每个节点编一个号(1,2,3,4…),然后按照规律重新连接链表,规律就是最左边和最右边连,然后最右边和次左边连,有一个奇偶关系,连接从外向内推进,用一个循环就行。此题有个坑, 可能有多余节点,即不在链表上的节点,所以不能直接用题目的n表示总节点数,应该用遍历链表后的编号最大值表示节点数。
代码:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
typedef pair<int, int> PII;
PII lian[maxn];
int id[maxn];
int main(int argc, char const *argv[]) {
int root, n, x;
cin >> root >> n;
for (int i = 0; i < n; i++) {
cin >> x;
cin >> lian[x].first >> lian[x].second;
}
int now = root, cnt = 1;
while (now != -1) {
id[cnt++] = now;
now = lian[now].second;
}
int N = cnt - 1;
int L = 1, R = N;
now = N;
cnt = 0;
while (L < R) {
if (cnt % 2 == 0) {
lian[id[now]].second = id[L];
now = L;
R--;
} else {
lian[id[now]].second = id[R];
now = R;
L++;
}
if (L == R) lian[id[L]].second = -1;
cnt++;
}
now = id[N];
while (now != -1) {
printf("%05d %d ", now, lian[now].first);
if (lian[now].second == -1)
cout << "-1" << endl;
else
printf("%05d\n", lian[now].second);
now = lian[now].second;
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
敏捷开发项目管理的一些心得
MySQL database
元宇宙医疗或将改变医疗格局
高数_证明_基本初等函数的导数公式
laravel database: query builder
赶紧进来修内功!!!带你认识C语言中各种进制数和原码反码补码.
VIT:Transformer进军CV的里程碑
方程组解的情况与向量组相关性转化【线代碎碎念】
pdf导出工具类
laravel数据库: 查询构造器
Spark cluster environment construction
10 Top Open Source Caching Tools for Linux in 2020
Solve the inexplicable problem of MySQL violently - restart the service!
【数学模型】TOPSIS
垃圾账号不胜其烦,设备指纹快速发现
Web3构架是怎么样的?
最稳定的淘宝商品详情接口
H. Huge Boxes of Animal Toys
laravel-实践
Taro小程序跨端开发入门实战