逆序栈问题

题目:给你一个栈,请你逆序这个栈,不能申请额外的数据结构,只能使用递归函数。如何实现?

详情参看《程序员代码面试指南》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());
		}

	}
}

 


版权声明:本文为qq_33204444原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。