pila problema inverso

Tema: darle una pila, se invierte la pila, no se puede aplicar para la estructura de datos adicional, utilice únicamente una función recursiva. ¿Cómo lograr?

Ver "Código del programador Entrevista de guía" detalles P7.

package com.gxu.dawnlab_algorithm8;

import java.util.Stack;

/**
 * 给你一个栈,请你逆序这个栈,不能申请额外的数据结构,只能
 * 使用递归函数。如何实现?
 * @author junbin
 *
 * 2019年7月12日
 */
public class ReverseStackUsingRecursive {
	public static void reverse(Stack<Integer> stack) {
		if (stack.isEmpty()) {
			return;
		}
		int i = getAndRemoveLastElement(stack);
		reverse(stack);
		stack.push(i);
	}

	public static int getAndRemoveLastElement(Stack<Integer> stack) {
		int result = stack.pop();
		if (stack.isEmpty()) {
			return result;
		} else {
			int last = getAndRemoveLastElement(stack);
			stack.push(result);
			return last;
		}
	}

	public static void main(String[] args) {
		Stack<Integer> test = new Stack<Integer>();
		test.push(1);
		test.push(2);
		test.push(3);
		test.push(4);
		test.push(5);
		reverse(test);
		while (!test.isEmpty()) {
			System.out.println(test.pop());
		}

	}
}

 

Publicado 61 artículos originales · ganado elogios 9 · Vistas a 30000 +

Supongo que te gusta

Origin blog.csdn.net/qq_33204444/article/details/95635079
Recomendado
Clasificación