PAT 甲级 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.

输入

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N ( ≤ 1 0 5 ≤10^5 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.

输出

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.

思路

就是将前K个字符反转,遍历即可

代码

#include<cstdio>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef struct node {
    
    
	int key;
	int next;
}link;
link list[1000000];
link ans[1000000];
int l = 100000;
void reverse(int s, int e)
{
    
    
	int flag = 0;
	while (s != e)
	{
    
    
		ans[s].key = list[s].key;
		ans[s].next = ans[l].next;
		ans[l].next = s;
		s = list[s].next;
	}
}
int main()
{
    
    
	int start, N, K;
	cin >> start >> N >> K;
	for (int i = 0; i < N; i++)
	{
    
    
		int b, k, n;
		cin >> b >> k >> n;
		list[b].key = k;
		list[b].next = n;
	}
	int n = N / K;
	int s = start;
	for (int i = 0; i < n * K; i++)
	{
    
    
		s = list[s].next;
	}
	ans[l].next = s;
	int yyy = s;
	s = start;
	for (int i = 0; i < n; i++)
	{
    
    
		int e = s;
		for (int j = 0; j < K; j++)
		{
    
    
			e = list[e].next;
		}
		reverse(s, e);
		l = s;
		s = e;
	}
	s = ans[100000].next;
	while (yyy != -1)
	{
    
    
		ans[yyy].key = list[yyy].key;
		ans[yyy].next = list[yyy].next;
		yyy = list[yyy].next;
	}
	while (s != -1)
	{
    
    
		printf("%05d %d ", s, ans[s].key);
		if (ans[s].next>= 0)
		{
    
    
			printf("%05d", ans[s].next);
		}
		else
		{
    
    
			printf("-1");
		}
		printf("\n");
		s = ans[s].next;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_45478482/article/details/120082170