PAT A1074 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.

给出一个常数K和单链表L,你需要把链表L上每K个元素进行反转,比如,给出L:1->2->3->4->5->6.如果K=3,那么你需要输出3->2->1->6->5->4.如果K=4,你需要输出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 (≤10^​5​​) 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.

每一个测试样例,第一行包含了第一个结点的地址,一个正数N(≤10^5)代表结点总量,一个正数K(≤N)代表需要反转的子链表长度。结点的地址是一个5位非负整数,NULL用-1来代表

之后有N行,每一行描述了一个结点,格式如图 

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.

对于每一个测试样例,输出结果链表,每一个结点占一行,输出格式和输入格式相同

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100010;
struct Node{
	int address,data,next;
	int order;//结点在链表上的序号,无效节点记为maxn 
}node[maxn];

bool cmp(Node a,Node b){
	return a.order<b.order;
}

int main(){
	for(int i=0;i<maxn;i++){
		node[i].order=maxn;
	}
	int begin,n,K,address;
	scanf("%d%d%d",&begin,&n,&K);
	for(int i=0;i<n;i++){
		scanf("%d",&address);
		scanf("%d%d",&node[address].data,&node[address].next);
		node[address].address=address;
	}
	int p=begin,count=0;
	while(p!=-1){
		node[p].order=count++;
		p=node[p].next;
	}
	sort(node,node+maxn,cmp);
	n=count;
	
	for(int i=0;i<n/K;i++){
		for(int j=(i+1)*K-1;j>i*K;j--){
			printf("%05d %d %05d\n",node[j].address,node[j].data,node[j-1].address);
		}
		//下面是每一块最后一个结点的next地址处理 
		printf("%05d %d ",node[i*K].address,node[i*K].data);
		if(i<n/K-1){//如果不是最后一块,就指向下一块的最后一个结点
			printf("%05d\n",node[(i+2)*K-1].address); 
		}else{
			if(n%K==0){//恰好是最后一个结点,输出-1 
				printf("-1\n"); 
			}else{//剩下的不完整的块按原先顺序输出
				printf("%05d\n",node[(i+1)*K].address);
				for(int i=n/K*K;i<n;i++){
					printf("%05d %d ",node[i].address,node[i].data);
					if(i<n-1) printf("%05d\n",node[i+1].address);
					else  printf("-1\n");
				} 
				
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38179583/article/details/86706907
今日推荐