首页 > 学院 > 开发设计 > 正文

[LeetCode] Implement Stack using Queues

2019-11-15 01:05:54
字体:
来源:转载
供稿:网友
[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 useonlystandard operations of a queue -- which means onlypush to back,peek/pop from front,size, andis emptyoperations 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).

这道题就不说了,和之前说过的那道implement Queue using Stack的思路差不多。

还是建立两个Queue之间互相转换就好,记得所写的算法运行后必须保证两个queue的其中一个队列为空。

我的答案这里把push写成了offer然后pop写成了poll,不过leetcode还是识别了哈哈。

因为我写的时候有参考java platform standard(http://docs.Oracle.com/javase/7/docs/api/java/util/Queue.html#peek())这里面还是写的offer/poll所以就……。

class MyStack {    LinkedList<Integer> a=new LinkedList<Integer>();    LinkedList<Integer> b=new LinkedList<Integer>();    // Push element x onto stack.    public void push(int x) {        if(a.size()==0){            a.offer(x);        }else{           if(a.size()>0){               b.offer(x);               int size=a.size();               while(size>0){                   b.offer(a.poll());                   size--;               }           }else if(b.size()>0){               a.offer(x);               int size=b.size();               while(size>0){                   a.offer(b.poll());                   size--;               }           }                    }    }    // Removes the element on top of the stack.     public void pop() {         if(a.size()>0){            a.poll();         }else if(b.size()>0){             b.poll();         }            }    // Get the top element.i    public int top() {        if(a.size()>0){            return a.peek();        }else if(b.size()>0){            return b.peek();        }        return 0;    }    // Return whether the stack is empty.    public boolean empty() {        return a.isEmpty()&b.isEmpty();    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表