Stacks - potatoscript/dsa GitHub Wiki

🧩 What is a Stack?

A stack is like a stack of plates 🍽️. You add plates to the top, and you also remove plates from the top. The last plate you add is the first plate you take off!

In computer science, this is called Last In, First Out (LIFO) β€” the last item added is the first one to be removed.


πŸ–ΌοΈ Visual Example:

Top β†’ [Plate 3] β†’ [Plate 2] β†’ [Plate 1] β†’ Bottom

If you add a new plate (let’s call it β€œPlate 4”), it goes on top:

Top β†’ [Plate 4] β†’ [Plate 3] β†’ [Plate 2] β†’ [Plate 1] β†’ Bottom

And when you remove a plate, you always remove from the top:

Take off Plate 4: Top β†’ [Plate 3] β†’ [Plate 2] β†’ [Plate 1] β†’ Bottom

🧠 Why Use a Stack?

  • βœ… Reversible actions: Think about undoing an action. A stack helps us go back in the order of actions.
  • βœ… Memory management: Helps in managing memory for things like function calls in programming.

πŸ§ƒ Real-World Analogy

Situation Stack Comparison
πŸ” Plate stack Add/remove plates from the top
πŸ›’ Grocery cart Last item put in the cart is the first to come out
🧒 Hat pile The last hat you place is the first one you take off

πŸ’» C# Code: Simple Stack

Define a Stack:

In C#, we can use the Stack<T> class to easily implement a stack:

Stack<string> plateStack = new Stack<string>();

Add Items to the Stack (Push):

plateStack.Push("Plate 1");
plateStack.Push("Plate 2");
plateStack.Push("Plate 3");

Remove Items from the Stack (Pop):

string topPlate = plateStack.Pop();  // Removes "Plate 3"
Console.WriteLine("Removed: " + topPlate);

Peek at the Top Item:

If you just want to see the top item without removing it, you can peek at it:

string topPlate = plateStack.Peek();  // Shows "Plate 2" without removing it
Console.WriteLine("Top plate: " + topPlate);

🧩 Operations in a Stack

Operation Description Time Complexity
Push Add an item to the top of the stack O(1)
Pop Remove the top item from the stack O(1)
Peek View the top item without removing it O(1)
IsEmpty Check if the stack is empty O(1)

πŸ‹οΈβ€β™€οΈ Stack in Action: Example

Push Operation (Adding Plates):

Stack<string> plateStack = new Stack<string>();
plateStack.Push("Plate 1");
plateStack.Push("Plate 2");
plateStack.Push("Plate 3");

Console.WriteLine("Stack after pushing plates:");
foreach (var plate in plateStack)
{
    Console.WriteLine(plate);
}

Output:

Plate 3
Plate 2
Plate 1

Pop Operation (Removing Plates):

string removedPlate = plateStack.Pop();
Console.WriteLine("Removed Plate: " + removedPlate);

Console.WriteLine("Stack after popping a plate:");
foreach (var plate in plateStack)
{
    Console.WriteLine(plate);
}

Output:

Removed Plate: Plate 3
Plate 2
Plate 1

🚨 Pitfalls to Avoid

  • ❌ Popping from an empty stack: You can’t pop an item from an empty stack, or you'll get an error. Always check if the stack is empty first.
if (plateStack.Count > 0)
{
    plateStack.Pop();
}
else
{
    Console.WriteLine("Stack is empty!");
}

πŸŽ“ Stack Use Cases in Programming

πŸ–₯️ Function Call Stack

When you run a program, each function call gets pushed onto the stack, and when a function finishes, it gets popped off.

πŸš— Undo/Redo Operations

Imagine editing a document:

  • When you make changes, those actions are pushed onto the stack.
  • When you undo the change, you pop it from the stack.

πŸ§ͺ Fun with Code: Undo Action in a Text Editor

Stack<string> undoStack = new Stack<string>();

// Adding changes
undoStack.Push("Added 'Hello' to text");
undoStack.Push("Added 'World' to text");

// Undo action
if (undoStack.Count > 0)
{
    string lastAction = undoStack.Pop();
    Console.WriteLine("Undoing: " + lastAction);
}

🧠 Time Complexity (Big O)

For Stack Operations:

  • Push: O(1) – Adding an item to the top is quick!
  • Pop: O(1) – Removing from the top is also quick!
  • Peek: O(1) – Viewing the top without changing the stack is also fast!

πŸ“œ Fun With Stack Challenges

🍎 Challenge 1: Plate Stack

Create a stack of 5 plates and remove them one by one, printing each plate’s name as you pop it off.

🧠 Challenge 2: Undo/Redo Simulation

Create a simple text editor program with a stack to simulate the undo feature. Add a few actions and then undo them.

🧹 Challenge 3: Balanced Parentheses Checker

Write a program that checks if a string of parentheses is balanced using a stack (i.e., every opening parenthesis has a corresponding closing parenthesis).


🧩 Types of Stacks

  • Single Stack: Standard stack, just one list of items.
  • Multiple Stacks: A stack of stacks β€” used in complex situations like evaluating expressions with multiple operations.
  • Array-Based Stack: When using arrays to store the stack.
  • Linked List-Based Stack: When using linked lists to store the stack.

πŸ“š Summary Time!

βœ… Stacks store data in a LIFO (Last In, First Out) order.
βœ… Add (Push) to the top, remove (Pop) from the top.
βœ… Use them for managing function calls, undo operations, and more!
βœ… Big O for stack operations: O(1) β€” they’re fast and efficient!


⚠️ **GitHub.com Fallback** ⚠️