๐งฑ Stack in C# โ Solving Problems the LIFO Way
A Stack<T>
is a Last-In-First-Out (LIFO) collection โ the last element added is the first one removed. It's commonly used in parsing, expression evaluation, and backtracking.
โ When to Use Stack
Use Case | Why Use Stack |
---|---|
Reversing elements | Natural LIFO behavior |
Nested structures / matching | e.g., parentheses, XML, recursion stack |
Backtracking | Push state, pop to revert |
Undo features | Store previous states |
โ๏ธ Declaring and Using Stack
var stack = new Stack<int>();
stack.Push(10); // Add to top
stack.Push(20);
int top = stack.Peek(); // Peek top (20)
stack.Pop(); // Remove top (20)
๐ Iterating Through Stack
foreach (int item in stack)
{
Console.WriteLine(item);
}
๐งช Interview Example 1: Valid Parentheses
public bool IsValid(string s)
{
var stack = new Stack<char>();
var map = new Dictionary<char, char> {
{')', '('}, {']', '['}, {'}', '{'}
};
foreach (char c in s)
{
if (map.ContainsValue(c))
stack.Push(c);
else if (map.ContainsKey(c))
{
if (stack.Count == 0 || stack.Pop() != map[c])
return false;
}
}
return stack.Count == 0;
}
๐งช Interview Example 2: Evaluate Reverse Polish Notation
public int EvalRPN(string[] tokens)
{
var stack = new Stack<int>();
foreach (var token in tokens)
{
if (int.TryParse(token, out int num))
stack.Push(num);
else
{
int b = stack.Pop();
int a = stack.Pop();
switch (token)
{
case "+": stack.Push(a + b); break;
case "-": stack.Push(a - b); break;
case "*": stack.Push(a * b); break;
case "/": stack.Push(a / b); break;
}
}
}
return stack.Pop();
}
๐ Summary
Feature | Syntax Example |
---|---|
Declare | new Stack<T>() |
Push | stack.Push(value) |
Pop | stack.Pop() |
Peek | stack.Peek() |
Count | stack.Count |
Iterate | foreach (var item in stack) |
Up next: Queue and Deque โ perfect for BFS traversal and sliding window problems!
Top comments (2)
These interview problems are reminding me of LeetCode ๐ .
try this if you get stuck during the interview. its an AI co-pilot that solves the questions for you so you can focus on the more important part of the interview, the communication part. its also a really good study tool: ghostengineer.com