[Leetcode]225. 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.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, 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).

这题目有点水。应该是cc150的原题。不知道意义何在。原题应该是没有top这个东西的。加了top稍微加了一点难度。

原本的做法也很简单,push是照常push的,复杂度O(n)。但是pop就不是照常poll了。如果你的queue里面有n个元素,那么你就poll n - 1 个,那剩下那个自然就是最后那个,符合stack LIFO的原理。poll出去的那些其实就直接push回去就行了。

譬如原来是 1 -> 2 -> 3 -> 4 -> 5。 你poll了四个并且把他们又push进来之后就成了 5 -> 1 -> 2 -> 3 -> 4。头元素5自然就是最后一个。top稍微增加了一点难度,你需要一个临时变量记录一下,譬如说你如果call top,你就做pop那样的操作并且记录一下头元素,如果再call top或者pop,如果有top元素的记录,就不再操作直接返回top。给出代码如下:

    /** Initialize your data structure here. */
    Integer top;
    Queue<Integer> queue;
    public MyStack() {
        queue = new LinkedList<Integer>();
        top = null;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if (top != null) {
            queue.add(top);
            top = x;
        } else {
            top = x;
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int res = top();
        top = null;
        return res;
    }
    
    /** Get the top element. */
    public int top() {
        if (top == null) {
            int popTimes = queue.size() - 1;
            while (popTimes > 0) {
                queue.add(queue.poll());
                popTimes--;
            }
            top = queue.poll();
        }
        
        return top;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return top == null && queue.isEmpty();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值