请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。

    实现 MyStack 类:

    void push(int x) 将元素 x 压入栈顶。
    int pop() 移除并返回栈顶元素。
    int top() 返回栈顶元素。
    boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

    注意:

    你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
    你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

    1. 输入:
    2. ["MyStack", "push", "push", "top", "pop", "empty"]
    3. [[], [1], [2], [], [], []]
    4. 输出:
    5. [null, null, null, 2, 2, false]
    6. 解释:
    7. MyStack myStack = new MyStack();
    8. myStack.push(1);
    9. myStack.push(2);
    10. myStack.top(); // 返回 2
    11. myStack.pop(); // 返回 2
    12. myStack.empty(); // 返回 False

    代码

    1. var MyStack = function () {
    2. this.queue = [];
    3. this._queue = [];
    4. };
    5. /**
    6. * @param {number} x
    7. * @return {void}
    8. */
    9. MyStack.prototype.push = function (x) {
    10. this.queue.push(x)
    11. };
    12. /**
    13. * @return {number}
    14. */
    15. MyStack.prototype.pop = function () {
    16. while (this.queue.length > 1) {
    17. this._queue.push(this.queue.shift());
    18. }
    19. let ans = this.queue.shift();
    20. while (this._queue.length) {
    21. this.queue.push(this._queue.shift());
    22. }
    23. return ans;
    24. };
    25. /**
    26. * @return {number}
    27. */
    28. MyStack.prototype.top = function () {
    29. return this.queue.slice(-1)[0];
    30. };
    31. /**
    32. * @return {boolean}
    33. */
    34. MyStack.prototype.empty = function () {
    35. return !this.queue.length;
    36. };
    37. /**
    38. * Your MyStack object will be instantiated and called as such:
    39. * var obj = new MyStack()
    40. * obj.push(x)
    41. * var param_2 = obj.pop()
    42. * var param_3 = obj.top()
    43. * var param_4 = obj.empty()
    44. */

    image.png