Data Structures

What is Stack Data Structure? Data Structure Tutorial

What is Stack Data Structure? Data Structure Tutorial

What is Stack Data Structure? Data Structure Tutorial

In this article, you will learn:

  • What is Stack?
  • Operations of Stack.
  • Applications of Stack

What is Stack?

A stack is a linear data structure. It follows the principle of Last In, First Out (LIFO). It means the last element inserted in the stack is removed first. 

LIFO Principle of Stack

In programming Language, putting an item inside the stack is known as PUSH, and taking the item out from the stack is known as POP. 

Example:

  1. Empty Stack.
  2. Push an element 7 (i.e inserting an element inside the stack)
  3. Push an element 2 (i.e inserting an element inside the stack)
  4. Push an element 10 (i.e inserting an element inside the stack)
  5. Pop an element(i.e removing the last element from the stack which is 10).

Similarly, the LIFO(Last In First Out) Principle Works. It works in the same way in all programming languages.

Operation of Stack

There are some basic operations that allow us to perform different actions on a stack:

  • Push: Insert an element to the top of the stack.
  • Pop: Remove an element from the top of the stack. 
  • IsEmpty: Verify if the stack is empty.
  • IsFull: Verify if the stack is full.
  • Peek: Fetch the value of the top item without removing the item from the stack.

Working of Stack Data Structures:

It works as follows:

  • A pointer called “Top” is used to keep the track of the element in the stack. 
  • Initialize the stack value to -1 so that we know when the value of the stack is -1, it is empty.
  • On inserting an element inside the stack, the value of the top increased by 1, and put the new element on the top. 
  • On popping an element, the value of the top decreased by 1. 
  • Before inserting an element, we have to check if the stack is full. 
  • Before removing an element, we have to check if the stack is empty. 

The time complexity of the stack is O(1).

Applications of Stack Data Structure:

The most common applications of the stack data structure are:

  • To reverse a word: Insert all the elements inside the stack and remove them from the stack. As stack works on the LIFO, you can easily get the letters in reverse order.
  • In compilers: Compilers use the stack to calculate the value of the expression by converting the expression to prefix and postfix form.
  • In browsers: The back button in a browser saves all the URLs in the stack.
Yamini  Sharma

I am working as a professional engineer in "HIghRadius Technologies Pvt. Ltd." Passionate about learning and exploring new technologies. Enthusiast in writing and sharing what I have in my knowledge bucket.