Stack is a Linear Data Structure that follows a LIFO (Last In First Out) principle.
To understand stack data structure let's take a real-life example of the arrangement of plates as shown below. You can observe that plate 1 is placed at the bottom and plate 2 is placed on top of plate 1 similarly plate 3 is placed on top of plate 2.
Now if you want to put one more late, the easiest way to arrange them is to put the next plate on top of all the other plates, and similarly, if you want to pick one plate then the easiest way is to pick the topmost plate from the stack of plates.
You can observe that the plate which you are putting, at last, is present on the top and you have to pick that plate first to take the other plates. So this is the basic idea of the LIFO principle of stack data structure.
Real-Life use of Stack Data Structure.
- Records of your phone logs use the Stack data structure to store all your call records so you get the most recent call details at the top.
- The browser saves your browsing history using the Stack data structure so you can see most of the details of the most recently visited page at the top.
- For recursive function calls, you have to be sure that your function calls do not each stack overflow exception.
You can implement the Stack data structure in two different ways,
- Stack Implementation using 1D Array.
- Stack Implementation using Singly Linked List.
![]() |
Push Operation |
pop(): It is used to remove an element from the top of the stack. You cannot directly remove the middle or last element from the stack.
![]() |
Pop Operation |
peek(): It is used to check which element is present at the top of the stack. It returns the value which is present a the top but it does not perform any changes.
All the above operations, push(), pop() and peek() take constant time O(1)
(getButton) #text=(Stack Implementation using Array) #icon=(link) #color=(#2339bd)
(getButton) #text=(Stack Implementation using Linked List) #icon=(link) #color=(#2339bd)
No comments:
Post a Comment