你的位置:首页 > Java教程

[Java教程][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 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).

     

     这道题就不说了,和之前说过的那道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();  }}