PAT Grade B 1025 Reverse Linked List 25 (points)

topic

Given a constant KK K and a singly linked list LL L , please write a program to reverse every KK K nodes in LL L. For example: Given that LL L is 1→2→3→4→5→6 and KK K is 3, the output should be 3→2→1→6→5→4; if KK K is 4, the output should be 4→3→2→1→5→6, that is, less than KK K elements are not inverted at the end.

Input format:

Each input contains 1 test case. Each test case is given first line of the address of a node, the total number of positive integers node NN N ( ≤ 1 0. 5 \ ^ Le. 5 10 1 0 ? . 5 ? ? ), And a positive integer KK K ( ≤ N \le N N ), that is, the number of sub-links that require reversal. The address of the node is a 5-bit non-negative integer, and the NULL address is represented by ? 1 -1 ? 1 .

Next, there are NN N lines, each in the format:

Address Data Next

Wherein Address a node address, Data is stored in the node integer data, Next the address of the next node.

Output format:

For each test case, the reversed linked list is output in order, each node on it occupies a row, and the format is the same as the input.

Input sample:

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

Code


#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
string format(int i)
{
    
    
	if (i < 10)
		return "0000" + to_string(i);
	else if (i < 100)
		return "000" + to_string(i);
	else if (i < 1000)
		return "00" + to_string(i);
	else if (i < 10000)
		return "0" + to_string(i);
	else if (i < 100000)
		return to_string(i);
}
int main()
{
    
    
	int BEGIN, n, K, i,addr,content,next,sum=0;
	cin >> BEGIN >> n >> K;
	int S[100005][2];
	for (i = 0; i < 100005; i++)
	{
    
    
		S[i][0] = 0;
		S[i][1] = 0;
	}
	i = -1;
	while (++i < n)
	{
    
    
		cin >> addr >> content >> next;
		S[addr][0] = content;
		S[addr][1] = next;
	}
	int** a = new int* [n];
	for (i = 0; i < n; i++)
		a[i] = new int[2];
	while (BEGIN != -1)
	{
    
    
		a[sum++][0] = BEGIN;
		a[sum-1][1] = S[BEGIN][0];
		BEGIN = S[BEGIN][1];
	}
	n = sum;
	if (K > 1)
	{
    
    
		for (i = 0; i < n; i += K)
			if (i + K <= n)
				reverse(a + i, a + i + K);
	}
	for (i = 0; i < n; i++)
		if (i + 1 != n)
			cout << format(a[i][0]) << " " << a[i][1] << " " << format(a[i + 1][0]) << endl;
		else
			cout << format(a[i][0]) << " " << a[i][1] << " " << "-1" << endl;
	return 0;
}

Question details link

Guess you like

Origin blog.csdn.net/qq_41985293/article/details/114983286