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.

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).
    • 思路:用队列实现栈,队列和栈的区别就是,栈是先进后出的,队列是先进先出的,队头元素相当于栈顶元素,那么栈的实现就好比是把队列先进去的那些又拿出来重新从后面进一次。
      public class MyStack {
          Queue<Integer>queue=new LinkedList<>();
          /** Initialize your data structure here. */
          public MyStack() {
              
          }
          
          /** Push element x onto stack. */
          public void push(int x) {
              queue.add(x);//队列和linkedlist一样的
             for(int i=0;i<queue.size()-1;i++)
             {
          	   queue.add(queue.remove());//把队头元素转为栈顶元素
             }
          }
          
          /** Removes the element on top of the stack and returns that element. */
          public int pop() {
               return queue.remove();//出队的反而是最后入队的元素
          }
          
          /** Get the top element. */
          public int top() {
              return queue.peek();//对头就是栈顶,即最后一个元素
          }
          
          /** Returns whether the stack is empty. */
          public boolean empty() {
              return queue.isEmpty();
          }
      }
      

        队列和栈之间是很巧妙的关系,队列转换为栈可以这样做,但是堆栈转换为队列的方法这样可不行。

posted @ 2017-06-01 17:28  牛虻爱吃饭  阅读(172)  评论(0编辑  收藏  举报