Stack
LIFO stack implementation with type safety
Description
A stack data structure implementation with last-in-first-out (LIFO) ordering. Provides type-safe operations for pushing and popping elements.
Features
- LIFO ordering
- Type safety
- Size tracking
- Iteration support
Code
class Stack<T> { private items: T[] = []; push(item: T): void { this.items.push(item); } pop(): T | undefined { return this.items.pop(); } peek(): T | undefined { return this.items[this.items.length - 1]; } isEmpty(): boolean { return this.items.length === 0; } size(): number { return this.items.length; } clear(): void { this.items = []; } toArray(): T[] { return [...this.items]; }}export default Stack;
import Stack from './Stack';const stack = new Stack<number>();stack.push(10);stack.push(20);stack.push(30);console.log('Size:', stack.size());console.log('Peek:', stack.peek());while (!stack.isEmpty()) { console.log('Popped:', stack.pop());}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.