![]() |
VOOZH | about |
In C# a Stack is a Collection that follows the Last-In-First-Out (LIFO) principle. It is used when we need last-in, first-out access to items. In C# there are both generic and non-generic types of Stacks. The generic stack is in the System.Collections.Generic namespace, while the non-generic stack is in System.Collections. The stack can dynamically store elements of the same or different types.
Example: This example demonstrates the basic working of Stack.
4 3 2 1
Below is the diagramatic Representation of Working of Stack:
The below diagram shows the Hierarchy of Stack class.
Stack class has three constructors which are used to create a stack which is as follows:
Letβs see how to create a stack using Stack() constructor:
Step 1: Include System.Collections namespace in your program with the help of using keyword
using System.Collections;
Step 2: Create a Stack using Stack class
Stack s = new Stack();
1. Adding Elements: We use push() method to insert elements in a stack.
Example: This example demonstrates how to create non-generic stack, add various elements to it and access them in Last-In-FIrst-Out (LIFO) Order.
10 1 geeksforgeeks Geek
2. Removing Elements:The Stack class provides two different methods to remove elements and the methods are listed below:
Example: This example displays the contents of the stack before and after removal.
Initial stack: For Geeks For Geeks Updated stack after Pop: Geeks For Geeks
3. Get the Topmost Element of the Stack: The Stack class provides two different methods to find the topmost element of the stack and the methods are listed below:
Example: This example demonstrates how to peek at the topmost element of a Stack.
The topmost element in the stack is: 30
4. Checking the Availability of Elements in the Stack: Stack class provide Contains() method to check if the element is present in the Stack or not.
Example:
The element 20 is present in the stack: True The element 100 is present in the stack: False
Generic Stack | Non-Generic Stack |
|---|---|
Generic stack is defined under System.Collections.Generic namespace. | Non-Generic stack is defined under System.Collections namespace. |
Generic stack can only store same type of elements. | Non-Generic stack can store same type or different types of elements. |
There is a need to define the type of the elements in the stack | There is no need to define the type of the elements in the stack. |
It is type-safe. | It is not type-safe. |