232. 用栈实现队列

leetCode队列
  • 一个入队栈,一个出队栈
  • 入队的时候正常
  • 出队的时候判断如果有元素就出,没有元素将入队栈的元素逆序导出到出队栈
var MyQueue = function() {
    // 入队栈
    this.pushStack = []
    // 出队栈
    this.popStack = []
    // 队列长度
    this.size = 0
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    // 入队栈添加元素
    this.pushStack.push(x)
    this.size++
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    // 判空
    if(this.empty()) return null
    // 判断出队栈是否有元素,没有元素要从入队栈中倒过去
    this.peek()
    this.size--
    // 返回删除的元素
    return this.popStack.pop()
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if(this.empty()) return null
    // 如果出队栈为空,就从入队栈中导入元素
    if (this.popStack.length === 0) {
        while(this.pushStack.length > 0) {
            this.popStack.push(this.pushStack.pop())
        }
    }
    // 返回最后一个元素
    return this.popStack[this.popStack.length  -  1]
};

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

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * 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
61
62
更新时间: 2022-03-25 17:04