PAT 2019年冬季 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

实现思路:

链表反转 根据K来定反转链表个数,基础题不详细赘述。

AC代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN=100010;
int bg,n,k;
struct node {
	int id,data,next;
} Node[MAXN];
vector<node> ans;

int main() {
	cin>>bg>>n>>k;
	int id;
	for(int i=0; i<n; i++) {
		scanf("%d",&id);
		Node[id].id=id;
		scanf("%d%d",&Node[id].data,&Node[id].next);
	}
	int cpy=bg;
	while(cpy!=-1) {
		ans.push_back(Node[cpy]);
		cpy=Node[cpy].next;
	}
	reverse(ans.begin(),ans.end());
	int group,rest;
	if(ans.size()%k==0) {
		group=ans.size()/k;
		rest=k;
	} else {
		group=ans.size()/k+1;
		rest=ans.size()%k;
	}
	int pos;
	for(int i=0; i<group; i++) {
		if(i==0) pos=rest-1;
		else pos+=k;
		int lowPos=(i==0?0:pos-k+1);
		for(int j=pos; j>=lowPos; j--) {
			printf("%05d %d ",ans[j].id,ans[j].data);
			if(j>lowPos) printf("%05d\n",ans[j-1].id);
			else {
				if(i<group-1) {
					printf("%05d\n",ans[pos+k].id);
				} else printf("-1\n");
			}
		}
	}
	return 0;
}
上一篇:A1097 Deduplication on a Linked List (25 分)


下一篇:赫夫曼树