Stacks
Stacks follow Last In, First Out (LIFO). Push adds to the top, pop removes from the top, peek reads without removing.
Example: Stacks across languages
javascript
class Stack {
constructor() { this.items = []; }
push(x) { this.items.push(x); }
pop() { return this.items.length ? this.items.pop() : null; }
peek() { return this.items.length ? this.items[this.items.length - 1] : null; }
isEmpty() { return this.items.length === 0; }
}
python
class Stack:
def __init__(self):
self.items = []
def push(self, x):
self.items.append(x)
def pop(self):
return self.items.pop() if self.items else None
def peek(self):
return self.items[-1] if self.items else None
def is_empty(self):
return len(self.items) == 0
java
import java.util.ArrayDeque;
public class StackDemo {
private ArrayDeque items = new ArrayDeque<>();
public void push(int x) { items.push(x); }
public Integer pop() { return items.isEmpty() ? null : items.pop(); }
public Integer peek() { return items.peek(); }
public boolean isEmpty() { return items.isEmpty(); }
}