<span>【题解】力扣 232. 用栈实现队列</span>

题目来源

232. 用栈实现队列

思路

方法一 双栈

创建两个栈,一个为入栈,一个为出栈。

队列是按照先进先出的原则执行的。

当队列执行入队操作,我们将入队的元素添加到入栈中。

当队列执行出队操作,我们首先要把入栈中的元素根据栈的先进后出原则,添加到出栈中,然后再将出栈中的栈顶元素弹出。

注意:在每次要执行出队操作前,都要先判断出栈的栈内元素是否为空,如果不为空,则直接将栈顶元素弹出即可,如果为空,则将入栈中的元素添加到出栈中。

class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;
    /** Initialize your data structure here. */
    public MyQueue() {
        in=new Stack<Integer>();
        out=new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out.isEmpty()){
            while(!in.isEmpty()) out.push(in.pop());
        }
        return out.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(out.isEmpty()){
            while(!in.isEmpty()) out.push(in.pop());
        }
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

参考来源

  1. 官方题解
全部评论

相关推荐

专业嗎喽:个人信息名字太大,合到电话邮箱那一栏就行,有党员写过党,剩下其他全删,站空太大了 把实习经历丰富,放最前面,然后是个人评价,技能之类的,然后是学校信息。项目经历最后面,可以就选一个自己擅长的。 现在是学校不是92就扣分的,没必要放前面。 然后现在看重实习经历>竞赛经历(校园经历)>课程项目经历
点赞 评论 收藏
分享
我要娶个什么名:学长你电脑闹鬼了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务