LeetCode 225 Implement Stack using Queues

来源:互联网 发布:2015nba体测数据 编辑:程序博客网 时间:2024/05/17 09:20

题目描述

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 back, peek/pop from front, size, 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).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.


分析

非常经典的题目,定义两个队列模拟栈的操作。总保持一个队列为空:

  1. push就插入到非空的队列中
  2. pop就把非空队列元素,依次放到另一个空队列中,只是最后一个元素弹出

代码

    class MyStack {        Queue<Integer> q1 = new LinkedList<Integer>();        Queue<Integer> q2 = new LinkedList<Integer>();        // Push element x onto stack.        public void push(int x) {            if (q1.isEmpty() && q2.isEmpty()) {                q1.add(x);            } else if (!q1.isEmpty()) {                q1.add(x);            } else {                q2.add(x);            }        }        // Removes the element on top of the stack.        public void pop() {            if (empty()) {                throw new IllegalStateException();            }            // q1、q2必有一个为空            if (q2.isEmpty()) {                while (!q1.isEmpty()) {                    int x = q1.remove();                    if (!q1.isEmpty()) {                        q2.add(x);                    }                }            } else if (q1.isEmpty()) {                while (!q2.isEmpty()) {                    int x = q2.remove();                    if (!q2.isEmpty()) {                        q1.add(x);                    }                }            }        }        // Get the top element.        public int top() {            if (empty()) {                throw new IllegalStateException();            }            int x = 0;            // q1、q2必有一个为空            if (q2.isEmpty()) {                while (!q1.isEmpty()) {                    x = q1.remove();                    q2.add(x);                }            } else if (q1.isEmpty()) {                while (!q2.isEmpty()) {                    x = q2.remove();                    q1.add(x);                }            }            return x;        }        // Return whether the stack is empty.        public boolean empty() {            if (q1.isEmpty() && q2.isEmpty()) {                return true;            }            return false;        }    }
2 0