剑指Offer 09. 用两个栈实现队列

剑指Offer队列
var CQueue = function() {
    // 入队栈
    this.pushStack = []
    // 出队栈
    this.popStack = []
    // 队列长度
    this.size = 0
};

/** 
 * @param {number} value
 * @return {void}
 */
CQueue.prototype.appendTail = function(value) {
    // 入队栈入元素
    this.pushStack.push(value)
    this.size++
};

/**
 * @return {number}
 */
CQueue.prototype.deleteHead = function() {
    // 判空
    if (this.size === 0) return -1
    // 如果出队栈为空,那么就从入队栈中push进去
    if (this.popStack.length === 0) {
        while(this.pushStack.length > 0) {
            this.popStack.push(this.pushStack.pop())
        }
    }
    // 长度-1
    this.size--
    // 返回被删除的元素
    return this.popStack.pop()
};

/**
 * Your CQueue object will be instantiated and called as such:
 * var obj = new CQueue()
 * obj.appendTail(value)
 * var param_2 = obj.deleteHead()
 */
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
更新时间: 2022-03-25 17:04