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:

    1. MyStack stack = new MyStack();
    2. stack.push(1);
    3. stack.push(2);
    4. stack.top(); // returns 2
    5. stack.pop(); // returns 2
    6. stack.empty(); // returns false

    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).

    题意

    使用队列Queue来实现栈Stack。要求只能使用队列的add/offer、remove/poll、peek、size、isEmpty方法。

    思路

    可使用双队列或单队列,直接上代码。


    代码实现 - 双队列

    1. class MyStack {
    2. private Queue<Integer> q1, q2;
    3. private int top;
    4. /** Initialize your data structure here. */
    5. public MyStack() {
    6. q1 = new LinkedList<>();
    7. q2 = new LinkedList<>();
    8. }
    9. /** Push element x onto stack. */
    10. public void push(int x) {
    11. q1.offer(x);
    12. top = x;
    13. }
    14. /** Removes the element on top of the stack and returns that element. */
    15. public int pop() {
    16. while (q1.size() > 1) {
    17. top = q1.poll();
    18. q2.offer(top);
    19. }
    20. int res = q1.poll();
    21. Queue<Integer> temp = q1;
    22. q1 = q2;
    23. q2 = temp;
    24. return res;
    25. }
    26. /** Get the top element. */
    27. public int top() {
    28. return top;
    29. }
    30. /** Returns whether the stack is empty. */
    31. public boolean empty() {
    32. return q1.isEmpty();
    33. }
    34. }

    代码实现 - 单队列

    1. class MyStack {
    2. private Queue<Integer> q;
    3. /** Initialize your data structure here. */
    4. public MyStack() {
    5. q = new LinkedList<>();
    6. }
    7. /** Push element x onto stack. */
    8. public void push(int x) {
    9. int size = q.size();
    10. q.offer(x);
    11. while (size != 0) {
    12. q.offer(q.poll());
    13. size--;
    14. }
    15. }
    16. /** Removes the element on top of the stack and returns that element. */
    17. public int pop() {
    18. return q.poll();
    19. }
    20. /** Get the top element. */
    21. public int top() {
    22. return q.peek();
    23. }
    24. /** Returns whether the stack is empty. */
    25. public boolean empty() {
    26. return q.isEmpty();
    27. }
    28. }