Solución

@rjnunezc_e48c1c70
·3/4/2026TypeScript
solution.tsTypeScript
class StackNode {
  constructor (
    public value: number,
    public next: StackNode | null = null
  ) {}
}

class Stack {
  public stack: StackNode | null;
  private static minValue: number;

  constructor () {
    this.stack = null;
    Stack.minValue = Infinity;
  }

  push(value: number): void {
    const newNode = new StackNode(value);

    if (!this.stack) {
      this.stack = newNode;
      Stack.minValue = this.stack.value
    } else {
      newNode.next = this.stack;
      this.stack = newNode;
      if (Stack.minValue > this.stack.value) {
        Stack.minValue = this.stack.value;
      }
    }
  }

  pop(): number | null {
    if (!this.stack) return null;
    const value = this.stack.value;
    this.stack = this.stack.next;
    let tempStackHead = this.stack;
    Stack.minValue = Infinity;
    while (tempStackHead) {
      if (Stack.minValue > tempStackHead.value) {
        Stack.minValue = tempStackHead.value;
      }
      tempStackHead = tempStackHead.next;
    }
    return value;
  }

  top(): number | null {
    if (!this.stack) return null;
    else return this.stack.value;
  }

  getMin(): number {
    return Stack.minValue;
  }
}


function minStack(operations: Array<["push" | "pop" | "top" | "getMin", number?]>): number[] {
  const results: number[] = [];

  const stack = new Stack();

  for (const operation of operations) {
    const [op = "", value = 0] = operation;

    switch(op) {
      case "push":
        stack.push(value);
        break;
      case "pop":
        stack.pop();
        break;
      case "top":
        results.push(stack.top());
        break;
      case "getMin":
        results.push(stack.getMin());
        break;
    }
  }

  return results;
}

// No modificar: necesario para evaluar el resultado.
export { minStack };
0respuestas
Respuestas
0

Aún no hay respuestas

¡Sé el primero en responder!

Escribir un comentario

Recuerda ser amable. Estás comentando la solución de otra persona. Comparte tu perspectiva de forma constructiva y respetuosa.

Debes iniciar sesión para publicar un comentario.
Markdown