C# Stack

In the C# coding language, the Stack<T> class is frequently employed for adding and removing elements. It operates based on the principle of a Stack that organizes elements in a Last In First Out (LIFO) manner. The Stack can contain duplicate elements and is located within the System.Collections.Generic namespace.

The design of the placeholder element includes a linear gradient background with specific colors, rounded corners, padding, and center alignment. Additionally, it features an icon with a certain font size and spacing, as well as text styled in a particular color and size.

In C#, the Stack class is frequently used for handling data in a Last In, First Out (LIFO) manner. It allows for efficient execution of various beneficial operations like adding, removing, and viewing elements.

Syntax:

It has the following syntax:

Example

Stack stack_name = new Stack();

In this particular format,

the

  • stack_name signifies the stack's name.
  • Key Operations of the C# Stack Class

The C# stack class provides the capability to execute various actions. A few examples include:

1) Push(T item) Function

In C#, the Push (T item) function is frequently used to add an element to the stack's top. This method adheres to the Last-In-First-Out (LIFO) concept, ensuring that the item added last will be the first one to be removed from the stack.

C# Stack Class Example Using push method

Let's consider a scenario to demonstrate the stack class by utilizing the push function in C#.

Example

Example

using System;

using System.Collections.Generic;

class C# Tutorial

{

    static void Main()

    {

        Stack<string> stack = new Stack<string>();

        stack.Push("Apple");

        stack.Push("Banana");

        stack.Push("Cherry");

        Console.WriteLine("Elements after Push:");

        foreach (var i in stack)

            Console.WriteLine(i);

    }

}

Output:

Output

Elements after Push:

Cherry

Banana

Apple

Explanation:

In this instance, we are forming a generic string stack that adds three elements ("Apple", "Banana", "Cherry") to it and displays the stack. Due to the Last In First Out (LIFO) nature of a stack, the most recently added item ("Cherry") appears first in the displayed result, succeeded by "Banana" and then "Apple".

2) Pop Function

In C# coding language, the pop method is frequently used to eliminate and retrieve the element from the stack's top.

C# Stack Class Example using the pop function

Let's explore a scenario to illustrate the stack class by utilizing the pop method in C#.

Example

Example

using System;

using System.Collections.Generic;

class pop

{

    static void Main()

    {

        Stack<int> s = new Stack<int>();

        s.Push(100);

        s.Push(200);

        s.Push(300);

        Console.WriteLine("Popped element: " + s.Pop());

        Console.WriteLine("Remaining elements:");

        foreach (var j in s)

            Console.WriteLine(j);

    }

}

Output:

Output

Popped element: 300

Remaining elements:

200

100

Output:

In this instance, we establish an integer stack, adding 100, 200, and 300 to it. Subsequently, the top value is removed and printed using Pop, resulting in 300 being returned. To conclude, the remaining elements, 200 and 100, are printed in Last In, First Out (LIFO) order.

3) Peek Function

In C#, it is frequently used to retrieve the element at the top of the stack without removing it.

C# Stack class Example using the peek function

Let's explore a basic illustration to showcase the stack class by utilizing the peek method in C#.

Example

Example

using System;

using System.Collections.Generic;

class C# Tutorial

{

    static void Main()

    {

        Stack<string> stack = new Stack<string>();

        stack.Push("Red");

        stack.Push("Green");

        stack.Push("Blue");

        Console.WriteLine("Top element: " + stack.Peek());

        Console.WriteLine("Stack after Peek:");

        foreach (var item in stack)

            Console.WriteLine(item);

    }

}

Output:

Output

Top element: Blue

Stack after Peek (unchanged):

Blue

Green

Red

Explanation:

In this instance, a string stack was constructed with elements "Red", "Green", and "Blue" being pushed onto it. Subsequently, the Peek method is employed to exhibit the uppermost item ("Blue") without removing it. Following this, the stack's contents are displayed, remaining unchanged: Blue, Green, Red.

4) Contains(T item) Function

In C# programming, the contains(T item) method is frequently used to check if a particular element is present in the stack. This method scans the stack to find the specified value and returns true if the element is found, otherwise, it returns false.

Here is an example demonstrating the usage of the contains function in the C# Stack class:

Example

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        Stack myStack = new Stack();

        myStack.Push("apple");
        myStack.Push("banana");
        myStack.Push("cherry");

        bool containsBanana = myStack.Contains("banana");

        Console.WriteLine("Does the stack contain 'banana'?: " + containsBanana);
    }
}

Let's consider an illustration to showcase the stack class utilizing the contains method in C#.

Example

Example

using System;

using System.Collections.Generic;

class stack

{

    static void Main()

    {

        Stack<int> st = new Stack<int>();

        st.Push(5);

        st.Push(10);

        st.Push(15);

        Console.WriteLine("Does the stack contain 10 in it: " + st.Contains(10));

        Console.WriteLine("Does the stack contain 20 in it: " + st.Contains(20));

    }

}

Output:

Output

Does the stack contain 10 in it: True

Does the stack contain 20 in it: False

Explanation:

In this instance, we establish a stack of integers by pushing elements 5, 10, and 15 onto it. Subsequently, we employ the Contains method to verify the presence of 10 and 20 within the stack. The result indicates True for 10 as it exists in the stack, and False for 20 as it does not.

5) Count Function

The count method in the C# programming language is frequently employed to determine the quantity of items in the stack. Put simply, it is utilized to compute the total number of elements within the stack.

C# Stack class Example using the count function

Let's consider a scenario to showcase the stack class by utilizing the count method in C#.

Example

Example

using System;

using System.Collections.Generic;

class counting

{

    static void Main()

    {

        Stack<char> stack = new Stack<char>();

        stack.Push('A');

        stack.Push('B');

        stack.Push('C');

        stack.Push('D');

        Console.WriteLine("Total elements in stack: " + stack.Count);

    }

}

Output:

Output

Total elements in stack: 4

Explanation:

In this instance, a character stack has been generated with 'A', 'B', 'C', and 'D' being pushed onto it. Following this, the Count method is utilized to display the total number of elements, which is 4.

6) Clear Function

In C# programming, the clear method is frequently used to remove all elements from the stack.

C# Stack class Example using the clear function

Let's explore a basic example to demonstrate the stack class by utilizing the clear method in C#.

Example

Example

using System;

using System.Collections.Generic;

class C# Tutorial

{

    static void Main()

    {

        Stack<string> stack = new Stack<string>();

        stack.Push("a");

        stack.Push("b");

        stack.Push("c");

        Console.WriteLine("Count before Clear: " + stack.Count);

        stack.Clear();

        Console.WriteLine("Count after Clear: " + stack.Count);

    }

}

Output:

Output

Count before Clear: 3

Count after Clear: 0

Explanation:

In this instance, we've initialized a string stack with elements "a", "b", and "c" being pushed onto it. Subsequently, the count method is employed to reveal that the stack contains 3 elements prior to its clearance. Following this, the Clear function is utilized to remove all elements, and a subsequent count operation confirms that the stack is now empty, containing 0 elements.

7) ToArray Function

In the C# coding language, the ToArray method is frequently used to duplicate the items of the stack into a fresh array.

In this C# Stack class illustration, we will demonstrate the application of the ToArray method. Let's explore how this function can be utilized within the context of a stack in C#.

Let's consider a scenario to showcase the stack class functionality by employing the ToArray method in C#.

Example

Example

using System;

using System.Collections.Generic;

class C# Tutorial

{

    static void Main()

    {

        Stack<int> stack = new Stack<int>();

        stack.Push(1);

        stack.Push(2);

        stack.Push(3);

        int[] arr = stack.ToArray();

        Console.WriteLine("Array elements:");

        foreach (int n in arr)

            Console.WriteLine(n);

    }

}

Output:

Output

Array elements:

3

2

1

Explanation:

In this instance, a stack containing integers is generated where 1, 2, and 3 are sequentially added. Following this, the ToArray method is applied to duplicate the stack into an array. Subsequently, the elements of the array are outputted in Last-In-First-Out (LIFO) order, resulting in the sequence 3, 2, 1.

C# Stack class Example using the Push, Pop, and Peek Operations

Let's examine a sample Stack<T> class that stores items through the Push function, deletes items with the Pop function, and traverses items using a for-each loop.

Example

Example

using System;  

using System.Collections.Generic;    

public class StackExample  

{  

    public static void Main(string[] args)  

    {  

        Stack<string> names = new Stack<string>();  

        names.Push("Albert");  

        names.Push("Peter");  

        names.Push("James");  

        names.Push("Michael");  

        names.Push("Robert");    

        foreach (string name in names)  

        {  

            Console.WriteLine(name);  

        }    

        Console.WriteLine("Peek element: "+names.Peek());  

        Console.WriteLine("Pop: "+ names.Pop());  

        Console.WriteLine("After Pop, Peek element: " + names.Peek());  

  

    }  

}

Output:

Output

Robert

Michael

James

Peter

Albert

Peek element: Robert

Pop: Robert

After Pop, Peek element: Michael

Explanation:

In this instance, a Stack of strings titled names has been established, containing multiple items via the Push function. The items are exhibited through a foreach loop, demonstrating the Last-In-First-Out (LIFO) sequence. Subsequently, the Peek function accesses the foremost item without eliminating it, whereas the Pop function eradicates the top item from the stack. Ultimately, the latest top item is showcased post the pop action.

Features of the Stack__PRESERVE_24__ class in C#

There are several features of the stack class in C#. Some of them are as follows:

  • In the C# stack class, we can include the elements using the Push method.
  • The top element can be retrieved and popped through Pop, or simply retrieved without removal through Peek.
  • It is not indexable.
  • It supports null (for reference types) and duplicate items.
  • We can have an empty stack or initialize it from a collection or an array.
  • The Stack<T> class grows dynamically as elements are pushed, but also has a capacity property to allow for optimization of memory.
  • Conclusion

In summary, the Stack class in C# proves to be a powerful class that operates on the Last In, First Out (LIFO) principle, making it preferable for various situations like data reversal, evaluating expressions, and managing undo actions. It provides functionalities like Push, Pop, and Peek, ensuring both type safety and efficient performance. Nonetheless, it solely exposes the element at the top of the stack. All in all, the Stack presents a straightforward and efficient approach for managing temporary or sequential data in C#.

C# Stack Class FAQs

1) How do we create a Stack in C#?

Creating a stack in C# involves utilizing the following syntax:

Generic stack:

Example

Stack<int> stack = new Stack<int>();

Non-generic stack:

Example

Stack stack = new Stack();.

The time complexities of stack operations in C# are as follows:

  • Push operation has a time complexity of O(1).
  • Pop operation also has a time complexity of O(1).
  • Peek operation, which allows you to view the top element without removing it, also has a time complexity of O(1).

In C# programming, the time complexity for stack operations like Push, Pop, and Peek methods is constant, meaning it is O(1).

3) What is the method to determine the count of elements in a Stack in C#?

We have the ability to utilize the Count property in C# to retrieve the total number of elements present in the stack.

4) Can we iterate through a Stack in C#?

Yes, we have the option to iterate by utilizing a foreach loop that will sequentially go through items in Last In, First Out (LIFO) order.

5) When to use a Stack in C# programming?

It is appropriate in scenarios where Last In First Out (LIFO) access is required, such as in undo operations, parsing mathematical expressions, or implementing backtracking algorithms.

Input Required

This code uses input(). Please provide values below: