剑指offer(05)用两个栈实现队列

参考:https://www.cnblogs.com/wanghui9072229/archive/2011/11/22/2259391.html

思路1:始终维护s1作为存储空间,以s2作为临时缓冲区。

入队时,将元素压入s1。

出队时,将s1的元素逐个“倒入”(弹出并压入)s2,将s2的顶元素弹出作为出队元素,之后再将s2剩下的元素逐个“倒回”s1。

思路2如:

入队时,先判断s1是否为空,如不为空,说明所有元素都在s1,此时将入队元素直接压入s1;如为空,要将s2的元素逐个“倒回”s1,再压入入队元素。

出队时,先判断s2是否为空,如不为空,直接弹出s2的顶元素并出队;如为空,将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。

见下面示意图:

剑指offer(05)用两个栈实现队列

 

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    //进栈
    public void push(int node) {
        //如果栈1为空,将栈2中的数据倒入到栈1
        if(stack1.isEmpty()){
            while(!stack1.isEmpty())
            stack1.push(stack2.pop());
        //然后将node压入栈
        }
        stack1.push(node);
    }
    //出队
    public int pop() {
        if(stack1.isEmpty()&&stack2.isEmpty())
            throw new RuntimeException("queue is empty");
        //如果栈1为空,直接输出栈2
        if(stack2.isEmpty()){
        //否则将栈1的值输入到栈2,再输出
        while(!stack1.isEmpty())
            stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
}