【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

解题思路:

链表转置问题,首先我们需要定义一个结构来存储这些数据的Address,Data,Next;如果我们想要节约时间的话,可以把一开始对应数组的下标当作是他的地址,这样的话查找就会块很多,查找如下:

for(int i = address;i!=-1;i = number[i].next){
		if(num

每K个数字就转置一次,所以可以用vector把每K个数据存放一次,再分别转置后凭借在一起即可。

易错点:

1. 测试点1是因为有好几组的数据需要转置,每个数据的末尾,指向的都是后一个数组的首部,你要注意的就是,你指向的后一个数据是否已经转置过了;

2. 测试点5是需要注意每次放在数组里面数据的个数;

代码:

#include
using namespace std;

typedef struct Node{
	int add;
	int weight;
	int next;
};

int main(){
	int address,N,K;
	cin>>address>>N>>K;
	Node number[100000];
	for(int i=0;i>index>>w>>next;
		number[index].add = index;
		number[index].weight = w;
		number[index].next = next;
	}
	
	vector t[N/K+1];
	vector result;
	int tip = 0;
	int num = 0;
	for(int i = address;i!=-1;i = number[i].next){
		if(num=0;j--){
					Node k;
					if(j!=0){
						k.add = t[i][j].add;
						k.next = t[i][j-1].add;
						k.weight = t[i][j].weight;
					}else{
						k.add = t[i][j].add;
						k.next = t[i+1][0].add;
						k.weight = t[i][j].weight;
					}
					result.push_back(k);
				}
			}else{
				for(int j=t[i].size()-1;j>=0;j--){
					Node k;
					if(j!=0){
						k.add = t[i][j].add;
						k.next = t[i][j-1].add;
						k.weight = t[i][j].weight;
					}else{
						k.add = t[i][j].add;
						k.next = -1;
						k.weight = t[i][j].weight;
					}
					result.push_back(k);
				}
			}
		}
	}
	for(int i=0;i

你可能感兴趣的:(PAT(甲级),c++,pat考试,链表)