C# Stack

A Stack works on the principle of Last In, First Out (LIFO). The last element added to the stack is the first one to be removed.

Feature of Stack

Push: Adds an element to the top of the stack.

Pop: Removes and returns the element from the top of the stack.

Peek: Returns the element at the top of the stack without removing it.

Count: Returns the number of elements in the stack.

Example:


using System;
using System.Collections.Generic;

class MyProgram
{
    static void Main()
    {
        // Create a new stack of strings (representing actions)
        Stack fruitsStack = new Stack();
        fruitsStack.Push("Apple");
        fruitsStack.Push("Banana");
        fruitsStack.Push("Manago");
        fruitsStack.Push("Orange");

        // Count the items in Stack
        int itemsInStack = fruitsStack.Count;
        Console.WriteLine("Count the items in Stack is "+itemsInStack);
        // Delete one item which added in last.
        string lastFruit = fruitsStack.Pop();  // Remove and get the last action
        Console.WriteLine("deleted Fruit: " + lastFruit);
        // Peeking top element from the stack
         Console.WriteLine("Peeking top element: " + fruitsStack.Peek());

    }
}

Output:

Count the items in Stack is 4
deleted Fruit: Orange
Peeking top element: Manago

When to Use Stacks?

1. You need to process elements in reverse order (e.g., undo/redo, depth-first search).

2. You need to maintain a history of operations and process the most recent one first.

Example:

  1. Undo functionality in text editors.
  2. Depth-first search (DFS) in graphs.