Implementing Stacks in C#

CsharpProgrammingServer Side Programming

Stack class is implemented in C# using Push and Pop operations.

Stack is used in C# to represents last-in, first out collection of object. The following are the methods of Stack class −

Sr.No.Method & Description
1public virtual void Clear();
Removes all elements from the Stack.
2public virtual bool Contains(object obj);
Determines whether an element is in the Stack.
3public virtual object Peek();
Returns the object at the top of the Stack without removing it.
4public virtual object Pop();
Removes and returns the object at the top of the Stack.
5public virtual void Push(object obj);
Inserts an object at the top of the Stack.
6public virtual object[] ToArray();
Copies the Stack to a new array.

Push operation adds elements.

Stack st = new Stack();
st.Push('A');
st.Push('B');
st.Push('C');
st.Push('D');

The pop operation removes elements from the stack.

st.Push('P');
st.Push('Q');

Here is an example showing how to work with Stack class and its Push() and Pop() method.

Example

 Live Demo

using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();

         st.Push('A');
         st.Push('B');
         st.Push('C');
         st.Push('D');

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

         st.Push('P');
         st.Push('Q');

         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 + " ");
         }
      }
   }
}

Output

Current stack:
D C B A
The next poppable value in stack: Q
Current stack:
Q P D C B A
Removing values....
Current stack:
C B A
raja
Published on 16-Aug-2018 12:49:30
Advertisements