LeetCode: use dos pilas para implementar la cola (implementación JS)

Descripción del Título

Ideas para resolver problemas

  • Inicializar usando dos matrices
  • Una matriz para almacenar operaciones de puesta en cola
  • Una matriz para almacenar operaciones de quitar de cola
  • La función enqueue empuja el valor ingresado por el sistema a la matriz A
  • La función de queue primero juzga si hay un elemento en la matriz de queue, y lo saca si hay alguno.
  • De lo contrario, inserte los elementos de la matriz A en la matriz B en orden inverso y luego salga

Código de implementación

var CQueue = function() {
    
    
    // 模拟入队
    this.stackA = [];
    // 模拟出队
    this.stackB = [];
};

CQueue.prototype.appendTail = function(value) {
    
    
    console.log("系统输入的数据:",value);
    this.stackA.push(value);
};

CQueue.prototype.deleteHead = function() {
    
    
    // 首先判断出队栈中是否有元素,有则出栈
    if (this.stackB.length) {
    
    
        return this.stackB.pop();
    } else {
    
    
        // 如果出队栈中没有元素,则判断入队栈中是否有元素
        while (this.stackA.length) {
    
    
            // 如果入队栈中有元素,则将入队栈倒序加入到出队栈
            this.stackB.push(this.stackA.pop());
        }
        if (this.stackB.length === 0) {
    
    
            return -1;
        } else {
    
    
            return this.stackB.pop();
        }
    }

};

Supongo que te gusta

Origin blog.csdn.net/sinat_41696687/article/details/115196397
Recomendado
Clasificación