C# Data Structures - Stack

Stack serves as a collection of elements. There are two main operations of Stack.
 
Push - Adds elements to the collection.
 
Pop - Removes elements from the collection.
 
Stack works in a LIFO (Last in, First Out) manner. It is considered a linear data structure. The push and pop operations occur only at one end of the structure.
 
Stack Class in C#
 
We have Stack class in C#. It represents a simple last-in-first-out (LIFO) non-generic collection of objects.
 
Namespace:
 
 
Assemblies
 
System.Collections.NonGeneric.dll, mscorlib.dll, netstandard.dll.
 
Stack<T> Class  (Generic Version)
 
Namespace:
System.Collections.Generic
Assemblies:
System.Collections.dll, System.dll, netstandard.dll
 
 
Example- Reverse a string using Stack 
 
Code
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace ReverseAStringUsingStack  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             Console.WriteLine("Enter a String:");  
  11.             string sInput = Console.ReadLine();  
  12.             string sOutput = ReverseAString(sInput);  
  13.   
  14.             Console.WriteLine("\n Reversed String is: " + sOutput);  
  15.             Console.Read();  
  16.         }  
  17.   
  18.         private static string ReverseAString(string sInput)  
  19.         {  
  20.             Stack<char> objStack = new Stack<char>();  
  21.             string sOutPut = string.Empty;  
  22.             if (sInput != null)  
  23.             {  
  24.                 int iInputLength = sInput.Length;  
  25.   
  26.                 for (int i=0;i<iInputLength;i++)  
  27.                 {  
  28.                     objStack.Push(sInput[i]);  
  29.                 }  
  30.                 
  31.                 while (objStack.Count != 0)  
  32.                 {  
  33.                     sOutPut += objStack.Pop();  
  34.                 }  
  35.             }  
  36.             return sOutPut;  
  37.         }  
  38.     }  
  39. }  
Output
 

Next Recommended Reading Binary Search Implementation Using C#