美文网首页
使用栈实现队列

使用栈实现队列

作者: 段段小胖砸 | 来源:发表于2021-07-09 09:22 被阅读0次

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty)。

public class MyQueue {
    private Stack<Integer> s1;//入栈
    private Stack<Integer> s2;//出栈
    //构造方法
    public MyQueue(){
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    //入栈
    public void push(int x) {
    /*
    1.首先给s1入栈
     */
        s1.push(x);
    }

    public int pop() {
    /*
    1.如果s2为空,则将s1(是否为空)全部的值先移动到s2
    2.如果s2有值,则直接弹出
     */
        if (s2.empty()){
            while(!s1.empty()){
                s2.push(s1.pop());
            }
        }
        //这个判断条件就是去除s1为空,从而导致s2也为空的情况
        if (!s2.empty()){
            return s2.pop();
        }
        return -1;
    }

    public int peek() {
        if (s2.empty()){
            while(!s1.empty()){
                s2.push(s1.pop());
            }
        }
        if (!s2.empty()){
            return s2.peek();
        }
        return -1;

    }

    public boolean empty() {
        if (s1.empty() && s2.empty()){
            return true;
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:使用栈实现队列

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