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.

C# Stack – Interview Questions

Q 1: What is Stack?
Ans: A LIFO (Last In First Out) collection.
Q 2: Method to add item?
Ans: Push().
Q 3: Method to remove item?
Ans: Pop().
Q 4: Method to view top item?
Ans: Peek().
Q 5: Stack belongs to which namespace?
Ans: System.Collections.

C# Stack – Objective Questions (MCQs)

Q1. Which method adds an element to the top of a stack?






Q2. Which method removes and returns the top element of the stack?






Q3. Which method returns the top element without removing it?






Q4. What type of data structure is a Stack?






Q5. What happens if you call Pop() on an empty stack?






Related C# Stack Topics