232. 用栈实现队列 + 栈 + 队列

232. 用栈实现队列

LeetCode_232

题目描述

方法一:在push时将原有栈的元素全部出栈然后再将当前元如入栈,最后再将第二个栈的元素入第一个栈

class MyQueue{
    int num;
    Deque<Integer> sta1, sta2;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        sta1 = new LinkedList<>();
        sta2 = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        while(!sta1.isEmpty()){
            sta2.push(sta1.pop());
        }
        sta1.push(x);
        while(!sta2.isEmpty()){
            sta1.push(sta2.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return sta1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return sta1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return sta1.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. 在peek或者push的时候,且此时出栈为空,则需要将入栈的所有元素进入出栈中
  2. 在push时只需要将元素进入入栈即可,起到了暂存元素的作用。
class MyQueue{
    int num;
    Deque<Integer> insta, outsta;//使用双端队列来模拟栈
    /** Initialize your data structure here. */
    public MyQueue() {
        insta = new LinkedList<>();
        outsta = new LinkedList<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        insta.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        
        return outsta.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(outsta.isEmpty()){
            while(!insta.isEmpty()){
                 outsta.push(insta.pop());
            }
        }
        return outsta.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outsta.isEmpty() && insta.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 @   Garrett_Wale  阅读(75)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示