其他分享
首页 > 其他分享> > 1074 Reversing Linked List (25 分)

1074 Reversing Linked List (25 分)

作者:互联网

卡点:

input:

00100 6 2

00000 4 99999

00100 1 -1

68237 6 -1

33218 3 00000

99999 5 68237

12309 2 33218

output:

00100 1 -1

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <queue>
using namespace std;
struct Node{
	int data;
	int next;
}L[100010];
int firstp, N, K;
void reverse(int p1, int p2){ 
	int pre = p1, now = L[p1].next, post;
	while(pre != p2){
		post = L[now].next;
		L[now].next = pre;
		pre = now; 
		now = post; 
	}
}
int main(){	
	scanf("%d %d %d", &firstp, &N, &K);
	int now, data, next;
	for(int i = 0; i < N; i++){
		scanf("%d %d %d", &now, &data, &next);
		L[now].data = data;
		L[now].next = next;
	}
	int p = firstp, legal = 0;
	while(p != -1){
		legal++; p = L[p].next;
	}
	int newp = firstp;
	if(K <= legal){		
		for(int i = 1; i < K; i++){
			newp = L[newp].next;
		}			
		int pre, p1, p2;
		pre = p1 = p2 = firstp;
		while(p1 != -1){
			int i = 1;
			for(; i < K; i++){
				if(L[p2].next == -1) break;
				p2 = L[p2].next;
			}					
			next = L[p2].next;
			if(i == K){	
				reverse(p1, p2);
				L[pre].next = p2;
			}else{
				L[pre].next = p1;
			}
			pre = p1;
			p1 = p2 = next;
			if(p1 == -1 && i == K) L[pre].next = -1;			
		}	
	}
	now = newp;
	while(L[now].next != -1){
		printf("%05d %d %05d\n", now, L[now].data, L[now].next);
		now = L[now].next;
	}
	printf("%05d %d -1\n", now, L[now].data);		
	return 0;
}

 

标签:pre,25,include,int,1074,List,next,now,data
来源: https://blog.csdn.net/wangxianhualian/article/details/99653568