美文网首页
用两个栈来形成一个队列

用两个栈来形成一个队列

作者: Hammy | 来源:发表于2018-03-08 09:40 被阅读0次

题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:一个栈用来进行push,另一个栈进行pop.
当进行pop的时候,将第一个栈所有元素都push到第二个栈中.
进行pop的时候,保证第二个栈不为空时进行pop.
代码:

public class TwoStackToQuene {
    Stack<Integer> stackOne = new Stack<Integer>();
    Stack<Integer> stackTwo = new Stack<Integer>();

    public void push(int node) {
        stackOne.push(node);
    }

    public int pop() {
        if (stackTwo.isEmpty()) {
            while (!stackOne.isEmpty()) {
                int node = stackOne.pop();
                stackTwo.push(node);
            }
        }
        return stackTwo.pop();
    }
}

相关文章

网友评论

      本文标题:用两个栈来形成一个队列

      本文链接:https://www.haomeiwen.com/subject/ormefftx.html