Estructura de datos que sigue el principio LIFO (Last In, First Out).
El último elemento en entrar es el primero en salir. Se utiliza en algoritmos y para la gestión de la memoria.
// Implementación de Pila class Pila<T> { private elementos: T[] = []; push(item: T): void { this.elementos.push(item); } pop(): T | undefined { return this.elementos.pop(); } peek(): T | undefined { return this.elementos[this.elementos.length - 1]; } isEmpty(): boolean { return this.elementos.length === 0; } size(): number { return this.elementos.length; } } // Uso: Validar paréntesis balanceados function validarParentesis(str: string): boolean { const pila = new Pila<string>(); const pares: Record<string, string> = { ')': '(', ']': '[', '}': '{' }; for (const char of str) { if ('([{'.includes(char)) { pila.push(char); } else if (')]}}'.includes(char)) { if (pila.pop() !== pares[char]) return false; } } return pila.isEmpty(); } validarParentesis('([{}])'); // true validarParentesis('([)]'); // false