【PAT甲级】1074 Reversing Linked List (25 point(s))

Given a constant K K K and a singly linked list L L L, you are supposed to reverse the links of every K K K elements on L L L. For example, given L being 1→2→3→4→5→6, if K = 3 K=3 K=3, then you must output 3→2→1→6→5→4; if K = 4 K=4 K=4, you must output 4→3→2→1→5→6.

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 ( ≤ 1 0 5 ≤10^5 105) which is the total number of nodes, and a positive K K K ( ≤ N ≤N N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by − 1 -1 1.

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

Address Key Next

where Address is the address of the node in memory, Key is an integer in [ − 1 0 5 , 1 0 5 ] [−10^5,10^5] [105,105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head 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 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

Method:

模拟链表模板,按组反转

Solution:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 链表节点
const int maxn = 1e6+10; 		
struct node {
    
    
	int address, key, next;
}nod[maxn]; 

int main() {
    
    
	int head1 = 0, n = 0, k = 0;
	cin >> head1 >> n >> k;

    // 初始化
	int address = 0, key = 0, next = 0;
	for (int i = 0; i < n; i++) {
    
    
		cin >> address >> key >> next;
		nod[address].address = address;
		nod[address].key = key;
		nod[address].next = next;
	}

    // 装入向量
	vector<node> list1;
	for (head1; head1 != -1; head1 = nod[head1].next)
		list1.push_back(nod[head1]);
	
    // 按组反转
	int sum = list1.size();
	for (int i = 0; i < (sum - sum % k); i += k)
		reverse(list1.begin() + i, list1.begin() + i + k);
	
    // 更新下标
	for (int i = 0; i < sum - 1; i++)
		list1[i].next = list1[i+1].address;
	list1[sum-1].next = -1;
	
    // 格式化打印
	for (int i = 0; i < sum - 1; i++)
		printf("%05d %d %05d\n", list1[i].address, list1[i].key, list1[i].next);
	printf("%05d %d -1\n", list1[sum-1].address, list1[sum-1].key);
	
	return 0;	
}

猜你喜欢

转载自blog.csdn.net/K_Xin/article/details/113772841