1074. Reversing Linked List (25)

题目:

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if 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 (<= 105) which is the total number of nodes, and a positive K (<=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.

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 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
注意:
1、创建两个数组,一个用来存储address为i的node的下一个node的address,另一个用来存储address为i的node的值。
2、然后用一个vector来建立链表,把每个node的address按照顺序存储起来,注意有可能输入的node里面有的并不在list之中,因此list的长度也许不是输入node的个数,case 6考察的就是这种情况。
3、最后按照要求输出,k个一组,先输出这一组中的第k个,他的下一个是第k-1个,这样一直向前输出,注意这一组第1个的下一个是下一组的第k个,不过要注意最后一组的以下两种情况:
     1)如果list的长度恰巧是k的整数倍,那么最后一组的第一个就是最后一个,那个输出最后一组的第一个时,它的下一个就是-1;
     2)如果list的长度不是k的整数倍,那么能进行reverse的就只有n/k向下取整次,而最后那一组中第一个的下一个就是剩下未能组成组的node里面的第一个,未能组成组的node也需要根据原始顺序依次输出。

代码:
//1074
#include<iostream>
#include<vector>
using namespace std;

int main()
{
	int start,n,k;
	int next[100000];//next[i] is the next node's address of the node with address i
	int val[100000];//val[i] is the value of the node with address i
	scanf("%d%d%d",&start,&n,&k);
	for(int i=0;i<n;++i)
	{
		int address;
		scanf("%d",&address);
		scanf("%d%d",val+address,next+address);
	}
	int cur=start;//current node
	vector<int>list;
	while(cur!=-1)
	{
		list.push_back(cur);
		cur=next[cur];
	}
	//recalculate the length of list(some input node may not in the list)
	n=list.size();//case 6
	int j;
	for(int i=0;i<n/k;++i)
	{
		for(j=(i+1)*k-1;j>i*k;--j)
			printf("%05d %d %05d\n",list[j],val[list[j]],list[j-1]);
		if(n%k==0 && i==n/k-1)
		{//when j is unfortually the last node
			printf("%05d %d -1\n",list[j],val[list[j]]);
			return 0;
		}
		else if(i==n/k-1)//if this is the last reverse part
			printf("%05d %d %05d\n",list[j],val[list[j]],list[(i+1)*k]);
		else
			printf("%05d %d %05d\n",list[j],val[list[j]],list[(i+2)*k-1]);
	}
	for(int i=(n/k)*k;i<n-1;++i)
		printf("%05d %d %05d\n",list[i],val[list[i]],list[i+1]);
	printf("%05d %d -1\n",list[n-1],val[list[n-1]]);//the last node
	return 0;
}

你可能感兴趣的:(考试,pat,浙江大学)