PAT乙级1025反转链表 25(分)

题目

给定一个常数 K K K 以及一个单链表 L L L ,请编写程序将 L L L 中每 K K K 个结点反转。例如:给定 L L L 为 1→2→3→4→5→6, K K K 为 3,则输出应该为 3→2→1→6→5→4;如果 K K K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K K K 个元素不反转。

输入格式:

每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N N N ( ≤ 1 0 5 \le 10^5 1 0 ? 5 ? ? )、以及正整数 K K K ( ≤ N \le N N ),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 ? 1 -1 ? 1 表示。

接下来有 N N N 行,每行格式为:

Address Data Next

其中 Address 是结点地址, Data 是该结点保存的整数数据, Next 是下一结点的地址。

输出格式:

对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

输入样例:

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

输出样例:

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

代码


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

题目详情链接

猜你喜欢

转载自blog.csdn.net/qq_41985293/article/details/114983286