关于算法-数据结构:PAT甲级2019年冬季考试-72-Block-Reversing

64次阅读

共计 2202 个字符,预计需要花费 6 分钟才能阅读完成。

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

题目限度:

题目粗心:

现给定一个链表 L,假设每 K 个位一块,最初有余 K 个的也为一块,当初要求将所有的块进行逆置,块内保障有序。

算法思路:

PAT 的动态链表的题目,要把握其中的一个特点就是,结点的地址和数值是绑定的,next 齐全不须要操心,最初将所有结点放在一片内存间断的区域天然就能够失去了。咱们这里采纳排序的办法来解决这个问题,给每一个结点赋值一个 flag 代表每一个结点的块号,id 代表每一个结点初始的绝对程序,那么排序规定就是先依据 flag 大的进行排序,flag 雷同的间接依照 id 进行排序即可。接下来就是 flag 和 id 的获取,对于 id 来说,链表的终点为 0,往后顺次累加,而 flag 为其 id/K,拍完序之后,间接输入即可,只须要留神 next 的输入,在最初一个结点得输入 -1,否则输入下一个结点的地址就行。

留神点:

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

提交后果:

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;
}

正文完
 0