leetcode 225. 用队列实现栈

思路:用两个队列,先放到s2中,然后把s1的全部放入s2中,再将s1和s2进行交换即可。

class MyStack {
    Deque<Integer> s1=new ArrayDeque<>();
    Deque<Integer> s2=new ArrayDeque<>();

    public MyStack() {

    }
    
    public void push(int x) {
        s2.addLast(x);
        while(!s1.isEmpty()){
            s2.addLast(s1.pollFirst());
        }
        Deque<Integer> tmp=s1;
        s1=s2;
        s2=tmp;
    }
    
    public int pop() {
        return s1.pollFirst();
    }
    
    public int top() {
        return s1.peekFirst();
    }
    
    public boolean empty() {
        return s1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
posted @   livingsu  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示