PAT 1025 反转链表 (25分)(Java)

题目描述

  给定一个常数 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,即最后不到 K 个元素不反转。

输入格式:

  每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N (≤10的5次方)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。

  接下来有 N 行,每行格式为:

Address Data Next

  其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。

输出格式:

  对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

输入样例:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

输出样例:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

代码

package com.hbut.pat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class Pat_1025 {
	static class Node{
		public int address;
		public int value;
		public int next;
		public Node(int address, int value, int next) {
			this.address = address;
			this.value = value;
			this.next = next;
		}
		@Override
		public String toString() {
			if(this.next!=-1)
				return String.format("%05d", address)
						+" "+value
						+" "+String.format("%05d", next);
			else
				return String.format("%05d", address)
						+" "+value
						+" "+String.format("%02d", next);
		}
	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] buf = bf.readLine().split(" ");
		int head = Integer.parseInt(buf[0]); 
		int n = Integer.parseInt(buf[1]);
		int f = Integer.parseInt(buf[2]);
		Node[] nodes = new Node[100000];
		for(int i=0;i<n;i++) {
			buf = bf.readLine().split(" ");
			int address = Integer.parseInt(buf[0]);
			int value = Integer.parseInt(buf[1]);
			int next = Integer.parseInt(buf[2]);
			nodes[address] = new Node(address, value, next);
		}
		forEachAndReverse(nodes,head,f);
	}
	private static void forEachAndReverse(Node[] nodes,int start,int reverse) {
		int index = start;
		List<Node> link1 = new LinkedList<>();
		List<Node> link2 = new LinkedList<>();
		link1.add(nodes[index]);
		while((index = nodes[index].next)!=-1) {
			link1.add(nodes[index]);		
		}
		int length = link1.size();
		int reverseTimes = length/reverse; 
		for(int i=1;i<=reverseTimes;i++) {
			for(int j=reverse-1;j>-1;j--) {
				link2.add(link1.remove(j));
			}
		}
		for(Node node:link1) {
			link2.add(node);
		}
		int addressTemp = -1;
		for(int i=length-1;i>-1;i--) {
			link2.get(i).next = addressTemp;
			addressTemp = link2.get(i).address;
		}
		for(Node node:link2) {
			System.out.println(node);
		}
	}
}

发布了108 篇原创文章 · 获赞 134 · 访问量 178万+

猜你喜欢

转载自blog.csdn.net/huanglei305/article/details/105138615
今日推荐