L2-022 重排链表 (25 分)(模拟链表)

给定一个单链表 $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;
}

暂无评论

发送评论 编辑评论


|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇