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 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).
      class MyStack {
        Queue<Integer> q = new LinkedList<Integer>();
        
        // Push element x onto stack.
        public void push(int x) {
            q.add(x);
            
            int n = q.size();
            while (n-- > 1)
                q.add(q.poll());
        }
    
        // Removes the element on top of the stack.
        public int pop() {
            return q.poll();
        }
    
        // Get the top element.
        public int top() {
            return q.peek();
        }
    
        // Return whether the stack is empty.
        public boolean empty() {
            return q.isEmpty();
        }
    
      }

    用一个queue即可,遇到要push的,先push到队尾,然后一边poll一边offer相当于除队尾外reverse。

  • Queue的remove(), poll()都是取出第一个element,用poll()更好因为如果为空可以返回null
  • Queue的offer(),add()都是加入新元素,用offer更有效率
  • Queue的peek(),element()都是查询第一个element,用peek更好因为如果为空可以返回null

另,stack有empty()和isEmpty()方法,源代码显示其实是一致的,只是后续引入了isEmpty()保留了empty方法

posted @ 2019-08-27 02:02  Schwifty  阅读(113)  评论(0编辑  收藏  举报