PAT(甲级)2019年冬季考试 7-2 Block Reversing

7-2 Block Reversing (25分)

Given a singly linked list L. Let us consider every K nodes as a block (if there are less than K nodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to reverse all the blocks in L. For example, given L as 1→2→3→4→5→6→7→8 and K as 3, your output must be 7→8→4→5→6→1→2→3.

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 size of a block. 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 8 3
71120 7 88666
00000 4 99999
00100 1 12309
68237 6 71120
33218 3 00000
99999 5 68237
88666 8 -1
12309 2 33218`

Sample Output:

71120 7 88666
88666 8 00000
00000 4 99999
99999 5 68237
68237 6 00100
00100 1 12309
12309 2 33218
33218 3 -1

题目限制:

PAT(甲级)2019年冬季考试 7-2 Block Reversing_第1张图片

题目大意:

现给定一个链表L,假定每K个位一块,最后不足K个的也为一块,现在要求将所有的块进行逆置,块内保证有序。

算法思路:

PAT的静态链表的题目,要把握其中的一个特点就是,结点的地址和数值是绑定的,next完全不需要操心,最后将所有结点放在一片内存连续的区域自然就可以得到了。我们这里采用排序的方法来解决这个问题,给每一个结点赋值一个flag代表每一个结点的块号 ,id代表每一个结点初始的相对顺序,那么排序规则就是先根据flag大的进行排序,flag相同的直接按照id进行排序即可。接下来就是flag和id的获取,对于id来说,链表的起点为0,往后依次累加,而flag为其id/K,拍完序之后,直接输出即可,只需要注意next的输出,在最后一个结点得输出-1,否则输出下一个结点的地址就行。

注意点:

  • 1、结点不一定都在链表上,得遍历一遍。
  • 2、地址为5位整数,得保证输出和输入一个格式。

提交结果:

PAT(甲级)2019年冬季考试 7-2 Block Reversing_第2张图片

AC代码:

#include
#include
#include
#include
#include

using namespace std;

struct Node{
    int address;
    int data;
    int next;
    int flag;// 每一个结点的块号 
    int id;// 每一个结点初始的相对顺序 
}nodes[100005];
vector list;

bool cmp(const Node &a,const Node &b){
    return a.flag!=b.flag?a.flag>b.flag:a.id

你可能感兴趣的:(算法-数据结构,c++,链表)