Stack Implementation in C#

1. Introduction

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first element to be removed. Conceptually, it can be compared to a stack of plates; the plate added most recently is the first to be used. In computing, stacks are used in various algorithms, function calls, and many other processes.

2. Implementation Steps

1. Create a class for the Stack.

2. Implement methods for basic operations:

- Push: Add an item to the top of the stack.

- Pop: Remove and return the top item from the stack.

- Peek: View the top item without removing it.

- IsEmpty: Check if the stack is empty.

3. Test the stack with these operations to ensure it works correctly.

3. Implementation in C#

using System;
using System.Collections.Generic;
public class Stack<T> {
    private List<T> elements = new List<T>();
    // Push item onto the stack
    public void Push(T item) {
        elements.Add(item);
    }
    // Pop item off the stack
    public T Pop() {
        if (IsEmpty()) {
            throw new InvalidOperationException("Stack is empty");
        }
        var item = elements[elements.Count - 1];
        elements.RemoveAt(elements.Count - 1);
        return item;
    }
    // Peek at the top item without removing it
    public T Peek() {
        if (IsEmpty()) {
            throw new InvalidOperationException("Stack is empty");
        }
        return elements[elements.Count - 1];
    }
    // Check if the stack is empty
    public bool IsEmpty() {
        return elements.Count == 0;
    }
}
public class Program {
    public static void Main() {
        Stack<int> stack = new Stack<int>();
        stack.Push(1);
        stack.Push(2);
        stack.Push(3);
        Console.WriteLine(stack.Peek());  // Should print 3
        Console.WriteLine(stack.Pop());   // Should print 3
        Console.WriteLine(stack.Peek());  // Should print 2
    }
}

Output:

3
3
2

Explanation:

1. A generic Stack class is created to allow stacks of any type to be instantiated.

2. The Push method adds an item to the end of the internal list, which represents the top of the stack.

3. The Pop method checks if the stack is empty. If it's not, it removes and returns the last item from the list (top of the stack). If the stack is empty, an exception is thrown.

4. The Peek method returns the last item from the list without removing it, allowing you to see the top of the stack.

5. The IsEmpty method returns a boolean indicating whether the internal list (and thus the stack) is empty.

6. In the Program class, we test the implementation by pushing numbers onto the stack, peeking to see the top element, and popping to remove the top element.

This provides a detailed understanding of the Stack implementation in C#.


Comments