PAT甲级1074 Reversing Linked List (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​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

二、解题思路

链表反转题,与一般的链表题类似,我们建立一个结构体表示结点,里面包含数据以及指向地址。用while循环构建链表,将地址存入vector<int> add中,随后建立一个循环,对每K个元素翻转一次,即把地址重新排列即可,最后输出即可。这种链表题一定要多做,做多了就很有感觉。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 100001;
struct Node
{
    
    
    int data, next;
}node[maxn];
int main()
{
    
    
    int first, N, K, tmp;
    vector<int> add;
    scanf("%d%d%d", &first, &N, &K);
    for(int i=0; i<N; i++)
    {
    
    
        scanf("%d", &tmp);
        scanf("%d%d", &node[tmp].data, &node[tmp].next);
    }
    tmp = first;
    while(tmp != -1)
    {
    
    
        add.push_back(tmp);
        tmp = node[tmp].next;
    }
    int sze = add.size();
    for(int i=0; i+K<=sze; i += K)    //有效链表元素数为size
    {
    
    
        reverse(add.begin()+i, add.begin()+i+K);
    }
    for(int j=0; j<sze-1; j++)
    {
    
    
        printf("%05d %d %05d\n", add[j], node[add[j]].data, add[j+1]);
    }
    printf("%05d %d -1\n", add[sze-1], node[add[sze-1]].data);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/108723684