LeetCode - 225. Implement Stack Using Queues

题目要求使用Queue来实现Stack,我们都知道Queue是FIFO,而Stack是FILO,为了解决这个问题,我们只要在add元素进Queue的时候把之前加进去的元素都poll出来然后再重新add进Queue即可,这样就是实现了FILO的操作。具体的函数实现见下面:


整体的代码如下:

class MyStack {
    Queue<Integer> queue;
    
    public MyStack(){
        queue = new LinkedList<Integer>();
    }
    
    // Push element x onto stack.
    public void push(int x) {
        queue.offer(x);
        for(int i = 0; i < queue.size() - 1; i++){
            queue.offer(queue.poll());
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        queue.poll();
    }

    // Get the top element.
    public int top() {
        return queue.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return queue.isEmpty();
    }
}

知识点:

1. 这种使用Stack实现Queue的问题和使用Queue实现Stack的问题都是非常容易考的问题,把它们的解题方法记一下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值