Solución
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