#1074. Reversing Linked List【链表】

原题链接

Problem Description:

Given a constant K K K and a singly linked list L L L, you are supposed to reverse the links of every K K K elements on L L L. For example, given L L L being 1→2→3→4→5→6, if K = 3 K =3 K=3, then you must output 3→2→1→6→5→4; if K = 4 K = 4 K=4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N N N ( ≤ 1 0 5 \leq 10^5 105) which is the total number of nodes, and a positive K K K ( ≤ N \leq N N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by − 1 -1 1.

Then N N N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

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

Sample Output:

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

Problem Analysis:

这里有一个很巧妙的方法,我们可以不直接对链表进行反转,转而将原有链表中的每一个节点的地址都存入一个 vector<int> 内,然后按照间隔 Kvector 反转,然后依次更新每个点的 next 指向下一个节点的地址,然后进行输出即可。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

const int N = 1e5 + 10;

int n, m;
int h, e[N], ne[N];

int main()
{
    
       
    scanf("%d%d%d", &h, &n, &m);

    for (int i = 0; i < n; i ++ )
    {
    
    
        int address, data, next;
        scanf("%d%d%d", &address, &data, &next);
        e[address] = data, ne[address] = next;
    }

    vector<int> q;
    for (int i = h; ~i; i = ne[i]) q.push_back(i);

    for (int i = 0; i + m - 1 < q.size(); i += m)
        reverse(q.begin() + i, q.begin() + i + m);

    for (int i = 0; i < q.size(); i ++ )
    {
    
    
        printf("%05d %d ", q[i], e[q[i]]);
        if (i + 1 == q.size()) puts("-1");
        else printf("%05d\n", q[i + 1]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/geraltofrivia123/article/details/121109999