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
- using System;
- using System.Collections.Generic;
-
- namespace ReverseAStringUsingStack
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter a String:");
- string sInput = Console.ReadLine();
- string sOutput = ReverseAString(sInput);
-
- Console.WriteLine("\n Reversed String is: " + sOutput);
- Console.Read();
- }
-
- private static string ReverseAString(string sInput)
- {
- Stack<char> objStack = new Stack<char>();
- string sOutPut = string.Empty;
- if (sInput != null)
- {
- int iInputLength = sInput.Length;
-
- for (int i=0;i<iInputLength;i++)
- {
- objStack.Push(sInput[i]);
- }
-
- while (objStack.Count != 0)
- {
- sOutPut += objStack.Pop();
- }
- }
- return sOutPut;
- }
- }
- }
Output