C# Program to Implement Stack with Push and Pop operations


Set stack with Push operation to add elements to the Stack −

Stack st = new Stack();

st.Push('A');
st.Push('M');
st.Push('G');
st.Push('W');

To Pop elements from the stack, use Pop() method −

st.Pop();
st.Pop();

The following is an example to implement a stack with Push and Pop operations −

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

Output

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements