LeetCode232.用栈实现队列

题目:

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

实现 MyQueue 类:

    void push(int x) 将元素 x 推到队列的末尾
    int pop() 从队列的开头移除并返回元素
    int peek() 返回队列开头的元素
    boolean empty() 如果队列为空,返回 true ;否则,返回 false

思路

使用双栈。

将一个栈当作入列的栈,用于压入 push 传入的数据;
另一个栈当作出列的栈,用于 pop 和 peek 操作。

代码:

class MyQueue {

    Stack<Integer> inStack ;
    Stack<Integer> outStack ;

    //将一个栈当作入列的栈,用于压入 push 传入的数据;
    //另一个栈当作出列的栈,用于 pop 和 peek 操作。
    public MyQueue() {
        outStack = new Stack<>();
        inStack = new Stack<>();
    }
    
    public void push(int x) {
        inStack.push(x);
    }
    
    public int pop() {
        //出列的栈为空,则需要从入列的栈取到数据
        if (outStack.isEmpty()) {
        //入列的栈非空,就把所有入列的栈转入到出列的栈
            inToOut();
        }
        return outStack.pop();
    }

    /**
        把所有入列的栈数据,转入到出列的栈
     */
    public void inToOut() {
        //这里要判断,入列的栈,是否已经为空
        while (!inStack.isEmpty()) {
            outStack.push( inStack.pop());
        }

    }

    /**
        查看出列的栈数据
     */
    public int peek() {
        if (outStack.isEmpty()) {
             inToOut();
        } 

        return outStack.peek();
    }
    
    public boolean empty() {
        return inStack.isEmpty() && outStack.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();
 */

posted on   乐之者v  阅读(9)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-01-04 ElastaticSearch -- es深度分页 searchAfter
2018-01-04 SpringBoot简单理解
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示