LeetCode - 232. Implement Queue using Stacks

本文介绍了一种利用两个栈实现队列的方法,并提供了详细的代码实现。通过这种方式,可以在不使用内置队列的情况下实现队列的基本操作,如push、pop、peek及判断队列是否为空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以用两个stack实现MyQueue这个类,首先要给这个类添加两个property,即两个stack,同时添加一个构造函数,在这个构造函数中对这两个stack进行初始化。

push(x) -- Push element x to the back of queue:

将元素push到stack2中;

pop() -- Removes the element from in front of queue:

我们使用stack1来pop元素,为此,首先我们要将stack2中的元素以逆序的方式添加到stack1当中去,可以另外写一个函数来实现这个功能。之后在每次pop的时候都先检查stack1是否为空,如果是的话就将stack2的元素全部放入stack1中,否则直接对stack1进行pop

peek() -- Get the front element:

与pop相似,只是将调用的函数变成peek;

empty() -- Return whether the queue is empty:

检查是否stack1和stack2都为空;

代码如下:

class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    
    // Constructor
    MyQueue(){
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public void stack2ToStack1(){
        while(!stack2.empty()){
            stack1.push(stack2.pop());
        }
    }
    
    // Push element x to the back of queue.
    public void push(int x) {
        stack2.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        if(stack1.empty()){
            stack2ToStack1();
        }
        stack1.pop();
    }

    // Get the front element.
    public int peek() {
        if(stack1.empty()){
            stack2ToStack1();
        }
        return stack1.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stack1.empty() && stack2.empty();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值