×

Stack Data Structure

The stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added to the end is removed first, and the element that is added first is removed at the end. There is only one end to insert and remove the element in the stack called the top end.

Stack

Example:

A good real-life example of a stack is the pile of dinner plates. When you have to take one plate from a pile, you pick the topmost plate and then the next plate. The last plate is picked at the end, which is placed first in a pile. The last plate is known as the base plate in the stack.

Stack

Stack operations

There are four types of operations in the stack.

  1. Push
  2. Pop
  3. Peek
  4. Update

Push: Push operation is used to insert a new element in the stack. Push operation is shown in the figure below.

Stack

Pop: Pop operation is used to delete an element in the stack. Pop operation is shown in the figure below.

Stack

Peek: When the data is received from a particular location in the stack, that operation is called peep operation.

Update: When the value of an element is changed in the stack, that operation is called update operation.

Overflow & Underflow Conditions

If the stack is empty and trying to delete an element from it, that situation is called underflow. If the stack is full and trying to add a new element to it, that situation is called overflow.

Applications of stack

  1. Expression evaluation: Stack is used to evaluating the prefix, postfix, and infix expressions.
Infix notationPrefix notationPostfix notation
A + B+ A BA B +
(A - C) * B*- A C BA C – B *
A + (B * C)+ A * BCA B C * +
(A + B) / (C + D)/ + A B – C DA B + C D - /
(A + (B * D)) / (C - (D * B))/ + A * B C – C * D BA B C * + C D B * - /
  • Expression conversion: An expression is represented in the prefix, postfix, or infix notation. The stack is used to convert the form of one expression to another form.
  • Syntax parsing: Many compilers use the stack to parsing the syntax expressions.
  • Memory management: It is also used in memory management.
  • Variable tracking: Stack is also used to track local variables in runtime.
  • Parenthesis checking: Stack is also used to check whether parenthesis is correctly open and closed or not.
  • String reverse: Stack is also used to reverse the string. In the string, we push the characters into the stack one by one and then pop the characters from the stack one by one.
  • Undo: Stack is also used to undo in text-editor.

Implementation in C language

#include <stdio.h>
 #include <stdlib.h>
 #define MAX 10   
int count = 0; // Creating a stack   struct stack 
{   
int items[MAX]; 
  int top; };  
 typedef struct stack st;  
 void createEmptyStack(st *s)
 {  
 s->top = -1; }   // Check if the stack is full int isfull(st *s) 
{   if (s->top == MAX - 1)    
 return 1;  
 else 
    return 0; 
}   // Check if the stack is empty int isempty(st *s)
 {  
 if (s->top == -1)    return 1; 
  else  
   return 0; }   // Add elements into stack
 void push(st *s, int newitem)
 {   if (isfull(s))
 {    
 printf("STACK FULL");
   } 
else 
{    
 s->top++;     s->items[s->top] = newitem;  
 }  
 count++; 
}   // Remove element from stack
 void pop(st *s) 
{   
if (isempty(s)) 
{    
 printf("\n STACK EMPTY \n");   
}
 else
 {   
  printf("Item popped= %d", s->items[s->top]);     s->top--;  
 }   count--;   
printf("\n"); 
}   // Print elements of stack void printStack(st *s)
 {  
 printf("Stack: "); 
  for (int i = 0; i < count; i++) 
{    
 printf("%d ", s->items[i]);  
 }
   printf("\n");
 }  
 // Driver code int main()
 { 
  int ch;  
 st *s = (st *)malloc(sizeof(st));
   createEmptyStack(s); 
  push(s, 1); 
  push(s, 3); 
  push(s, 4); 
  printStack(s);  
 pop(s);  
 printf("\nAfter popping out\n"); 
  printStack(s); 
}

Related Topics

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Merge Sort

Merge Sort is one of the most widely used sorting algorithms, and it is based on the Divide and Conquer principle. A problem is subdivided into multiple sub-problems in this method....

8 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Dynamic memory allocation of structure in C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

5 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Interval Tree

Interval Tree Interval Tree: The concept is to increase a Binary Search Tree self-balancing such as Red Black Tree, and AVL Tree, so that every feature can be completed in time O(Logn). Each Interval...

4 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.