Hello friends,
In the previous article, we have gone through how to choose the right data structure. If you want to refer to it, you may go to Data Structure And Algorithm - Choosing The Right Data Structure
Today we are going to implement the custom stack.
Let’s begin with defining the stack.
Stack
Stack is one of the most basic data structures that allows access only to the last element inserted. It follows Last in first out (LIFO).
![Data Structure And Algorithm]()
Below diagram illustrates Push and Pop operations in Stack.
![Data Structure And Algorithm]()
Following are some of the Important methods and properties used in stack.
- Insert/Push() – Inserts an element into Stack
- Remove/Pop() - Remove an element from Stack
- MakeEmpty() – Clears the stack
- Top/Peek() – Returns the last inserted element from Stack
- isEmpty() – Check if Stack is empty or not
- IsFull() - Check if Stack is full or not
Time Complexity
Stack can be implemented using Linked List and Array. The complexity is determined as follows.
Linked list with a pointer on the head
- Insert: O(1)
- Delete: O(1)
Array
- Insert: O(n), amortized time O(1)
- Delete: O(1)
To clarify, the amortized analysis considers both the costly and less costly operations together over the whole series of operations of the algorithm. This may include accounting for different types of input, length of the input, and other factors that affect its performance.
Algorithm
Push
Pop
Peek
IsFull
IsEmpty
In the above paragraph, we’ve gone through the algorithms used in Stack. Now let’s see how can we implement them using C#
Implementation using C#
Push
Pop
Peek
IsFull
IsEmpty
Summary
You can refer to the working demo here.
In today’s article, we have learned about various methods and properties involved in designing stack followed by the time complexity of key stack operations. We looked into different algorithms used in the most common stack methods. Towards end, we have seen how the stack operations can be implemented using C#.
Hope this article was useful to you. You can let me know for any comment and feedback.