Stacks in C#

Introduction

Greetings, Space Explorer! Today, we're drawing back the curtains on Stacks in C#, a crucial data structure. A stack is like a pile of dishes: you add a dish to the top (Last In) and take it from the top (First Out). This Last-In, First-Out (LIFO) principle exemplifies the stack. C# executes stacks effortlessly using the Stack class from the System.Collections.Generic namespace. This lesson will illuminate the stack data structure, its operations, and its applications in C#. Are you ready to start?

Utilizing Stacks in C#

To create a stack, C# employs a built-in data structure known as a Stack. For the push operation, we use Push(), which adds an element to the stack's end. For the pop operation, there's the Pop() function that removes the last element, simulating the removal of the 'top' element in a stack. Here's how it looks:

using System;
using System.Collections.Generic;

public class StackExample
{
    public static void Main(string[] args)
    {
        Stack<string> stack = new Stack<string>(); // A new empty stack

        // Push operations
        stack.Push("John");
        stack.Push("Mary");
        stack.Push("Steve");

        stack.Pop(); // Pop operation removes 'Steve'
        Console.WriteLine(string.Join(" -> ", stack)); // Outputs: John -> Mary
    }
}

In the example provided, we push John, Mary, and Steve into the stack and then pop Steve from the stack.

Advanced Stack Operations

Stack operations go beyond merely Push and Pop. For example, to verify if a stack is empty, we can check if the Count property is 0. If it is, that means the stack is empty. To peek at the top element of the stack without popping it, we use the Peek() method.

Here's an example:

using System;
using System.Collections.Generic;

public class StackOperations
{
    public static void Main(string[] args)
    {
        Stack<string> stack = new Stack<string>();
        stack.Push("Steve");
        stack.Push("Sam");

        Console.WriteLine(stack.Peek()); // Outputs: 'Sam'

        Console.WriteLine(stack.Count == 0); // Outputs: False
        stack.Pop(); // Remove 'Sam'
        stack.Pop(); // Remove 'Steve'
        Console.WriteLine(stack.Count == 0); // Outputs: True
    }
}

In this example, Sam is added (pushed), and then the topmost stack element, which is Sam, is peeked at.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal