1. 程式人生 > >PAT 1025 反轉鏈表

PAT 1025 反轉鏈表

接下來 pro text ans str size using htm pin

https://pintia.cn/problem-sets/994805260223102976/problems/994805296180871168

給定一個常數 K 以及一個單鏈表 L,請編寫程序將 L 中每 K 個結點反轉。例如:給定 L 為 1→2→3→4→5→6,K 為 3,則輸出應該為 3→2→1→6→5→4;如果 K 為 4,則輸出應該為 4→3→2→1→5→6,即最後不到 K 個元素不反轉。

輸入格式:

每個輸入包含 1 個測試用例。每個測試用例第 1 行給出第 1 個結點的地址、結點總個數正整數 N (≤)、以及正整數 K (≤),即要求反轉的子鏈結點的個數。結點的地址是 5 位非負整數,NULL 地址用 ? 表示。

接下來有 N 行,每行格式為:

Address Data Next

其中 Address 是結點地址,Data 是該結點保存的整數數據,Next 是下一結點的地址。

輸出格式:

對每個測試用例,順序輸出反轉後的鏈表,其上每個結點占一行,格式與輸入相同。

輸入樣例:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

輸出樣例:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

代碼:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e6 + 10;
int st, N, K;

struct Node {
    int address;
    int val;
    int nx;
};

Node n;
vector<Node> l;
vector<Node> ans;
Node add[maxn];

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

    int first = st;
    while(first != -1) {
        l.push_back(add[first]);
        first = add[first].nx;
    }

    int sz = l.size();
    int temp = K-1;
    while(temp < sz) {
        for(int i = temp; i > temp - K; i --) {
            ans.push_back(l[i]);
        }
        temp += K;
    }
    for(int i = temp - K + 1; i < sz; i ++)
        ans.push_back(l[i]);

    for(int i = 0; i < sz; i ++) {
        ans[i].nx = ans[i + 1].address;
        if(i != sz - 1)
            printf("%05d %d %05d\n", ans[i].address, ans[i].val, ans[i].nx);
        else
            printf("%05d %d -1\n", ans[i].address, ans[i].val);
    }

    return 0;
}

  用 $add$ 先存下來每一個節點的信息 用 $add$ 的下標存它的頭 然後把順序的鏈表存在 $l$ 裏面 最後進行反轉 輸出的時候每一個的 $nx$ 更新為下一個的 $address$ 看題解才明白的 本來想自己寫但是寫的亂七八糟 最近太愛犯困 不能玩手機偷懶了!!! :(

PAT 1025 反轉鏈表