;

C# Stack<T>


The Stack collection in C# is a data structure that stores items in a Last-In-First-Out (LIFO) order. It’s ideal for scenarios where the last item added is the first one to be removed, such as reversing operations, managing states, or backtracking. In this tutorial, we’ll explore the Stack in C#, understand its functionality through examples, discuss use cases, and illustrate its practicality with a real-world example.

Introduction

In C#, the Stack class is part of the System.Collections.Generic namespace and provides a way to store data in a LIFO order. When an item is added to the stack, it’s placed on the "top". To retrieve or remove an item, only the most recently added (top) item is accessible. Stacks are helpful for specific types of tasks where this LIFO behavior aligns with the requirement, such as managing undo operations in an application or performing depth-first search in algorithms.

Creating and Initializing a Stack

You can initialize a Stack in C# with or without initial values. Here’s a simple example of creating an empty stack and one initialized with values.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Creating an empty Stack of integers
        Stack<int> numberStack = new Stack<int>();

        // Initializing a Stack with values
        Stack<string> fruitStack = new Stack<string>(new string[] { "Apple", "Banana", "Cherry" });

        Console.WriteLine("Stack created with initial fruits:");
        foreach (var fruit in fruitStack)
        {
            Console.WriteLine(fruit);
        }
    }
}

Adding, Accessing, and Removing Elements

Adding Elements (Push)

The Push method adds an element to the top of the stack.

numberStack.Push(10);
numberStack.Push(20);
numberStack.Push(30);

Accessing Elements (Peek)

The Peek method allows you to see the top element without removing it from the stack.

int topElement = numberStack.Peek(); // Output: 30
Console.WriteLine($"Top element: {topElement}");

Removing Elements (Pop)

The Pop method removes and returns the top element from the stack.

int removedElement = numberStack.Pop(); // Output: 30
Console.WriteLine($"Removed element: {removedElement}");

Use Cases for Stack

  • Undo/Redo Operations: In text editors, the Stack can be used to store a sequence of operations that allow users to undo or redo their actions.
  • Expression Parsing: Often used in mathematical expression evaluators to manage operators and operands.
  • Backtracking Algorithms: In-depth first search algorithms, stack helps track the nodes or states visited.
  • Browser History Management: Stores visited URLs so that users can navigate backward through their browsing history.

Real-World Example: Browser History Navigation

A typical use case for a stack is managing browser history. Each time a user navigates to a new page, the current page is pushed onto the history stack. When the user clicks “Back,” the last page visited is “popped” from the stack and displayed.

Example

using System;
using System.Collections.Generic;

class BrowserHistory
{
    private Stack<string> historyStack = new Stack<string>();

    public void VisitPage(string url)
    {
        historyStack.Push(url);
        Console.WriteLine($"Visited: {url}");
    }

    public void Back()
    {
        if (historyStack.Count > 1)
        {
            historyStack.Pop(); // Pop the current page
            string previousPage = historyStack.Peek(); // Peek to get the previous page
            Console.WriteLine($"Back to: {previousPage}");
        }
        else
        {
            Console.WriteLine("No previous pages to go back to.");
        }
    }

    public void ShowHistory()
    {
        Console.WriteLine("\nBrowser History:");
        foreach (var page in historyStack)
        {
            Console.WriteLine(page);
        }
    }
}

class Program
{
    static void Main()
    {
        BrowserHistory browserHistory = new BrowserHistory();

        // Visiting pages
        browserHistory.VisitPage("www.homepage.com");
        browserHistory.VisitPage("www.section.com");
        browserHistory.VisitPage("www.article.com");

        // Going back
        browserHistory.Back();

        // Show the current history
        browserHistory.ShowHistory();
    }
}

Explanation

  1. VisitPage: This method pushes a new URL onto the history stack each time the user visits a new page.
  2. Back: When called, this method removes the current page from the stack and then peeks at the previous page to display it as the active page.
  3. ShowHistory: Displays the full browser history from top to bottom, showing the most recently visited pages first.

Using a stack in this scenario makes it easy to implement backtracking functionality, giving users a smooth experience when navigating through pages.

Key Takeaways

  • LIFO Order: Stack follows a Last-In-First-Out order, making it useful for situations where the last item needs to be processed first.
  • Common Operations: Includes Push to add, Pop to remove, and Peek to view the top element without removal.
  • Memory Efficient: Stacks are memory-efficient for small, temporary storage requirements.
  • Perfect for Backtracking: Ideal for scenarios like undo functionality, algorithm backtracking, and navigation history.

Summary

The Stack in C# is a straightforward yet powerful data structure, essential for scenarios requiring LIFO ordering. Its operations, such as Push, Pop, and Peek, offer an efficient way to manage temporary data. From managing browser history to implementing undo actions, Stack provides a practical solution to numerous common programming challenges. Understanding how to apply Stack effectively can help developers simplify complex state management tasks in a variety of applications.