题目描述
一个栈一次压入了1、2、3、4、5,那么从栈顶到栈底分别为5、4、3、2、1.将这个栈转置后,从栈顶到栈底为1、2、3、4、5,
解题思路
空间复杂度为O(n)
生成一个辅助栈,依次从原来栈中弹出压入辅助栈中,返回最后结果。
递归方法
不利用辅助栈,递归调用取得栈底元素的子函数然后将其压入原有栈中。空间复杂度为O(1),时间复杂度为O(n)
程序实现
public class Solution {
/**
* 逆置一个栈,O(n)时间,O(n)空间
*
* @param stack
* @return
*/
public Stack<Integer> reverseStack(Stack<Integer> stack) {
Stack<Integer> res = new Stack<>();
if (stack == null || stack.isEmpty())
return res;
while (!stack.isEmpty()) {
res.add(stack.pop());
}
return res;
}
/**
* 逆置一个栈,O(n)时间,O(1)空间
*
* @param stack
* @return
*/
public Stack<Integer> reverseStack1(Stack<Integer> stack) {
if (stack == null || stack.isEmpty())
return stack;
int i = getAndRemoveBottomElement(stack);
reverseStack1(stack);
stack.push(i);
return stack;
}
/**
* 取得栈底元素
*
* @param stack
* @return
*/
private int getAndRemoveBottomElement(Stack<Integer> stack) {
int result = stack.pop();
if (stack.isEmpty())
return result;
int last = getAndRemoveBottomElement(stack);
stack.push(result);
return last;
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack);
System.out.println(new Solution().reverseStack1(stack));
}
}