Reverse stack problem

Topic: give you a stack, you reverse the stack, can not apply for additional data structure, only use a recursive function. How to achieve?

See "Programmer Code Interview Guide" P7 details.

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());
		}

	}
}

 

Published 61 original articles · won praise 9 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_33204444/article/details/95635079