Push vs pop in stack class in C#


Stack class represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items.

The following is the property of Stack class −

  • Count − Gets the number of elements in the stack.

Push Operation

Add elements in the stack using the Push operation −

Stack st = new Stack();

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

Pop Operation

The Pop operation removes elements from the stack starting from the element on the top.

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

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements