关于LeetCode中Implement Stack using Queues一题的理解

题目如下:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
    题目要求使用队列的基本操作实现栈的基本操作,需要注意的是java中Queue是一个抽象类,我们如果需要使用队列相关操作的话,应该使用LinkedList类。

    思路也是很简单,我们只需要在push的时候做一些手脚,每次有新元素offer进来的时候,我们就把它之前的元素通过offer(poll)操作放到队列后面去,这样就变相将最新的元素一直保持在队列的首部。这样,我们在进行pop和top操作的时候就可以直接调用linkedList中的poll和peek实现这些功能。老规矩,已Accepted的代码如下:

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

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

    // Get the top element.
    public int top() {
        if(stack.isEmpty()){
            return -1;
        }else{
            return stack.peek();
        }
    }
    // Return whether the stack is empty.
    public boolean empty() {
        return stack.isEmpty();
    }
}
    这道题是有Editorial Solution的,地址在这里:https://leetcode.com/articles/implement-stack-using-queues/ 。里面有图有真相,大家自己去看就能看懂。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值