Stack Data Structure Introduction.

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.
There are basically three important operations that you can perform on the Stack and with the help of these operations on the stack, you can solve many complex coding problems. These operations are:

push(): It is used to push any element inside the given stack. It is the rule of stack data structure that you cannot directly push an element in between or at the bottom of the stack. You can push it on the top of the stack.

Image of push operation in Stack
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.

Image of Pop Operation on 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)

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS