PAT L2-022 重排链表

https://pintia.cn/problem-sets/994805046380707840/problems/994805057860517888

给定一个单链表 L1​​→L2​​→⋯→Ln1​​→Ln​​,请编写程序将链表重新排列为 Ln​​→L1​​→Ln1​​→L2​​→⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤)。结点的地址是5位非负整数,NULL地址用−表示。

接下来有N行,每行格式为:

Address Data Next

其中Address是结点地址;Data是该结点保存的数据,为不超过1的正整数;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 <bits/stdc++.h>
using namespace std;

const int maxn = 2e5 + 10;
int st, N;

struct Node{
    int nx;
    int address;
    int val;
}node[maxn];

vector<Node> line;
map<int, int> mp;
vector<Node> ans;

int main() {
    scanf("%d%d", &st, &N);
    Node n;
    for(int i = 0; i < N; i ++) {
        scanf("%d%d%d", &n.address, &n.val, &n.nx);
        node[n.address] = n;
    }

    int last = st;
    while(last != -1) {
        line.push_back(node[last]);
        last = node[last].nx;
    }

    int cnt = line.size();
    for(int i = cnt - 1; i >= (cnt - cnt / 2); i --) {
        printf("%05d %d %05d
", line[i].address, line[i].val, line[cnt - 1 - i].address);
        if(cnt - 1 - i == (cnt - 1) / 2)
            printf("%05d %d -1
", line[cnt - 1 - i].address, line[cnt - 1 - i].val);
        else
            printf("%05d %d %05d
", line[cnt - 1 - i].address, line[cnt - i - 1].val, line[i - 1].address);
    }
    if(cnt % 2) printf("%05d %d -1
", line[(cnt / 2)].address, line[(cnt / 2)].val);
    return 0;
}

  

原文地址:https://www.cnblogs.com/zlrrrr/p/10483526.html