力扣232—用栈实现队列(思路+代码)

发布于:2023-01-10 ⋅ 阅读:(530) ⋅ 点赞:(0)

链接👇
栈实现队列

思路:创建两个栈,入队:元素先入a。出队:b中为空且a不为空时,让a中元素入b(保证了后入的元素后出)

1.创建两个栈

 	Stack<Integer> a;
    Stack<Integer> b;
    public MyQueue() {
        a = new Stack<>();
        b = new Stack<>();
    }

2.入队

public void push(int x) {
        a.push(x);
    }

3.出队

 public int pop() {
        if(b.isEmpty()){//b中全部出完了 才能把a入b,保证后入后出,先入先出
         while(!a.isEmpty()){
            b.push(a.pop());
            }
        }
        return b.pop();
    }

4.查看栈顶

 public int peek() {
         if(b.isEmpty()){
         while(!a.isEmpty()){
            b.push(a.pop());
            }
        }
        return b.peek();
    }

完整代码👇

class MyQueue {
    Stack<Integer> a;
    Stack<Integer> b;
    public MyQueue() {
        a = new Stack<>();
        b = new Stack<>();
    }
    
    public void push(int x) {
        a.push(x);
    }
    
    public int pop() {
        if(b.isEmpty()){//b中全部出完了 才能把a入b,保证后入后出,先入先出
         while(!a.isEmpty()){
            b.push(a.pop());
            }
        }
        return b.pop();
    }
    
    public int peek() {
         if(b.isEmpty()){
         while(!a.isEmpty()){
            b.push(a.pop());
            }
        }
        return b.peek();
    }
    
    public boolean empty() {
        return (a.isEmpty() && b.isEmpty());
    }
}

如果对你有所帮助,一键三连!

运行结果👇
在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到