C# Stack


Release date:2023-09-06 Update date:2023-10-13 Editor:admin View counts:239

Label:

C# Stack

The Stack represents a collection of last-in, first-out objects. Use the stack when you need last-in-first-out access to items. When you add an item to the list called a push element, when you remove an item from the list, itis called a pop-up element.

Methods and properties of the Stack class

The following table lists some common properties of Stack class:

Attribute

Description

Count

Gets the number of elements contained in the Stack.

The following table lists some common methods of Stack.

Serial number

Method name & description

1

Public virtual void Clear (); removes all elements from the Stack.

2

Public virtual bool Contains (object obj); determines whether an element is in Stack.

3

Public virtual object Peek (); returns the object at the top of the Stack without removing it.

4

Public virtual object Pop (); removes and returns the object at the top of the Stack.

5

Public virtual void Push (object obj); add an object to the top of the Stack.

6

Public virtual object [] ToArray (); copy Stack into a new array.

Example

The following example demonstrates the use of Stack:

Example

using System;
using System.Collections;
namespace CollectionsApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();
            st.Push('A');
            st.Push('M');
            st.Push('G');
            st.Push('W');

            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
                Console.Write(c + " ");
            }
            Console.WriteLine();

            st.Push('V');
            st.Push('H');
            Console.WriteLine("The next poppable value in stack: {0}",
            st.Peek());
            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
               Console.Write(c + " ");
            }
            Console.WriteLine();
            Console.WriteLine("Removing values ");
            st.Pop();
            st.Pop();
            st.Pop();

            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
               Console.Write(c + " ");
            }
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A

Powered by TorCMS (https://github.com/bukun/TorCMS).