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.node

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.ios

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

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.less

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

題目限制:

image.png

題目大意:

現給定一個鏈表L,假定每K個位一塊,最後不足K個的也爲一塊,如今要求將全部的塊進行逆置,塊內保證有序。ide

算法思路:

PAT的靜態鏈表的題目,要把握其中的一個特色就是,結點的地址和數值是綁定的,next徹底不須要操心,最後將全部結點放在一片內存連續的區域天然就能夠獲得了。咱們這裏採用排序的方法來解決這個問題,給每個結點賦值一個flag表明每個結點的塊號 ,id表明每個結點初始的相對順序,那麼排序規則就是先根據flag大的進行排序,flag相同的直接按照id進行排序便可。接下來就是flag和id的獲取,對於id來講,鏈表的起點爲0,日後依次累加,而flag爲其id/K,拍完序以後,直接輸出便可,只須要注意next的輸出,在最後一個結點得輸出-1,不然輸出下一個結點的地址就行。spa

注意點:

  • 一、結點不必定都在鏈表上,得遍歷一遍。
  • 二、地址爲5位整數,得保證輸出和輸入一個格式。

提交結果:

image.png

AC代碼:

#include<cstdio>
#include<string>
#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct Node{
    int address;
    int data;
    int next;
    int flag;// 每個結點的塊號 
    int id;// 每個結點初始的相對順序 
}nodes[100005];
vector<Node> list;

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

int main(){
    int begin,N,K;
    scanf("%d %d %d",&begin,&N,&K);
    Node node;
    for (int i = 0; i < N; ++i) {
        scanf("%d %d %d",&node.address,&node.data,&node.next);
        nodes[node.address] = node;
    }
    int num = 0;
    while(begin!=-1){
        nodes[begin].id = num;
        nodes[begin].flag = num/K;
        ++num;
        list.push_back(nodes[begin]);
        begin = nodes[begin].next;
    }
    sort(list.begin(),list.end(),cmp);
    for(int i=0;i<list.size();++i){
        printf("%05d %d ",list[i].address,list[i].data);
        if(i<list.size()-1){
            printf("%05d\n",list[i+1].address);
        } else {
            printf("-1");
        }
    }
    return 0;
}
相關文章
相關標籤/搜索