Stack

The Stack follows the LIFO principle, it means Last In First Out which works as the last added
element to the stack collection is available to remove first. It is like disks are placed one over
another in a single pile.

It has the following methods:

- Push() method to add the elements

- Pop() method to remove the elements on a stack

- Peek () method to read the last element.

Example 1: Stack collection adding and removing the element.

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args)
    {
      Stack st = new Stack();
      st.Push(100);
      st.Push(true);
      st.Push(" Hi  ");
      st.Push(23.5);
      foreach(object m in st) {
        Console.Write($ " {
          m
        } ");
      }
      Console.WriteLine();
      Console.WriteLine($ " Last Element is: {
        st.Peek()
      } ");
      st.Pop();
      foreach(object m in st) {
        Console.Write($ " {
          m
        } ");
      }
      Console.WriteLine();
      Console.WriteLine($ " Last Element after pop is: {
        st.Peek()
      } ");
    }
  }
}

 

The output will be:

23.5 Hi True 100
Last Element is: 23.5
Hi True 100
Last Element after removing element is: Hi

 

 

Related Tutorials