PAT 甲级 1074 Reversing Linked List

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

算法思想
把链表先串起来,然后有序放入数组中,每k为倒序一下,然后读出即可,这显然是做题的方式,链表并没有变,只是改变了信息输出的位置。如果要使用链表的方式,需要标记一个链表的前驱和后继,然后一步一步将链表反向,又要考虑k位的问题,稍微有点啰嗦,有时间自己可以自己探究。

/**
* Copyright(c)
* All rights reserved.
* Author : csdn写完这道题就睡觉
* Description : JZU PAT test Level: A 
*/
#include 
using namespace std;
struct Node{
	int adr;
	int data;
	int next;
};
Node nodes[100001];
Node nodes_array[100001];
int main()
{
	int i,j,start,n,k,adr;
	cin>>start>>n>>k;
	for(i=0;i<n;i++)
	{
		scanf("%d",&adr);
		nodes[adr].adr=adr;
		scanf("%d %d",&nodes[adr].data,&nodes[adr].next);
	}
	i=0;
	adr=start;
	while(adr!=-1) //把链表顺序放入数组中 
	{
		nodes_array[i]=nodes[adr];
		adr=nodes[adr].next;
		i++;
	}
	n=i;
	int l=0,r=k-1;
	Node temp;
	while(r<n)
	{
		for(i=l,j=r;i<j;i++,j--)
		{
			temp=nodes_array[i];	
			nodes_array[i]=nodes_array[j];
			nodes_array[j]=temp;
		}
		l+=k;
		r+=k;
	}
	for(i=0;i<n-1;i++)
	{
		printf("%05d %d %05d\n",nodes_array[i].adr,nodes_array[i].data,
		nodes_array[i+1].adr);
	}
	printf("%05d %d -1\n",nodes_array[n-1].adr,nodes_array[n-1].data);
	return 0;
}

你可能感兴趣的:(PAT,OJ试题)