Stacks
A stack is a Last-In, First-Out (LIFO) data structure. The last element added is the first one removed — like a stack of plates.
Core Operations
| Operation | Description | Time |
|---|---|---|
Push |
Add to top | O(1) |
Pop |
Remove from top | O(1) |
Peek |
View top without removing | O(1) |
Stack in C
var stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");
stack.Push("Third");
Console.WriteLine(stack.Peek()); // "Third"
Console.WriteLine(stack.Pop()); // "Third"
Console.WriteLine(stack.Pop()); // "Second"
Console.WriteLine(stack.Count); // 1
Example: Balanced Parentheses Checker
A classic stack problem — check if brackets in a string are balanced:
public static bool IsBalanced(string input)
{
var stack = new Stack<char>();
var pairs = new Dictionary<char, char>
{
{ ')', '(' }, { ']', '[' }, { '}', '{' }
};
foreach (char ch in input)
{
if (ch is '(' or '[' or '{')
{
stack.Push(ch);
}
else if (pairs.ContainsKey(ch))
{
if (stack.Count == 0 || stack.Pop() != pairs[ch])
return false;
}
}
return stack.Count == 0;
}
// Usage
Console.WriteLine(IsBalanced("{[()]}")); // True
Console.WriteLine(IsBalanced("{[(])}")); // False
Console.WriteLine(IsBalanced("((())")); // False
Common Use Cases
- Undo/Redo — push actions onto a stack, pop to undo
- Expression parsing — compilers use stacks to evaluate expressions
- Backtracking — DFS, maze solving, browser history
- Call stack — method calls in your program use a stack internally