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 (≤105) 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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。