225. 用队列实现栈

leetCode队列

https://leetcode-cn.com/problems/implement-stack-using-queues/ (opens new window)

  • 两个队列,一个负责接收元素,然后将其他的元素弹出到后面
  • 两个指针互换
  • 删除的时候,识别队头
var MyStack = function() {
    // 正规队列
    this.queue1 = []
    // 入栈队列
    this.queue2 = []
    // 栈长度
    this.size = 0
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    // q2入栈
    this.queue2.push(x)
    // q1有元素就倒过去
    while(this.queue1.length) {
        this.queue2.push(this.queue1.shift())
    }
    // 交换q1和q2,确保q1是正规队列,q2是空的
    let temp = this.queue2
    this.queue2 = this.queue1
    this.queue1 = temp
    // 长度+1
    this.size++
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
    // 长度-1
    this.size--
    // q1队头出列
    return this.queue1.shift()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
    return this.queue1[0]
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return this.size === 0
};

/**
 * Your MyStack object will be instantiated and called as such:
 * var obj = new MyStack()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.empty()
 */
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
更新时间: 2022-03-25 17:04