PAT 甲 1074 反转链表 Reversing Linked List

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if 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 (≤10
​5
​​ ) which is the total number of nodes, and a positive K (≤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.

Then 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

题意:
给定一个常数 K 和一个单链表 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。
1、本题中可能包含不在链表中的节点,这些节点无需考虑。
输入格式
第一行包含头节点地址,总节点数量 N 以及常数 K。
节点地址用一个 5 位非负整数表示(可能有前导 0),NULL 用 −1 表示。
接下来 N 行,每行描述一个节点的信息,格式如下:
Address Data Next
其中 Address 是节点地址,Data 是一个整数,Next 是下一个节点的地址。
C++:

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int head,ne[N],e[N],idx;
int num[N];
void init(int head_address){
    head = head_address;
    idx = 0;
}
int main(){
    int a,n,k;
    cin>>a>>n>>k;
    init(a);
    for(int i = 0;i<n;i++){
         int aa;
         cin>>aa;
         cin>>e[aa]>>ne[aa];
    }
    int list[N],sum=0;
    while(a!=-1){
        list[sum++] = a;
        a = ne[a];
    }
    for(int i = 0;i<sum;i++) num[i]=list[i];
    for(int i = 0;i+k<=sum;i+=k){
        reverse(num+i,num+i+k);
    }
    for(int i = 0;i<sum;i++){
        if(i!=sum-1)printf("%05d %d %05d\n",num[i],e[num[i]],num[i+1]);
        else printf("%05d %d -1",num[i],e[num[i]],num[i+1]);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值