1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
52

Exploring the Fundamentals and Applications of Stack Data Structures

Updated on 23/08/2024440 Views

Introduction

The Stack is a significant topic within the Computer Science family. You will need to be well-versed in the Stack to pass competitive exams such as the GATE. This article will provide you with comprehensive knowledge about Stacks, and we will define stack data structure. Additionally, we think the notes for the CSE topics will further your understanding of the Stack.

An example of a linear data structure that adheres to the Last-In-First-Out (LIFO) concept is a stack in data structure. The Queue has two ends (front and back), while the Stack only has one. There is just one pointer in it, the top pointer, which points to the stack's top element. Each time an element is added to the stack, it is added at the top and can only be removed from the stack. Put differently, a stack can be described as a container that allows insertion and deletion from the top, or end, of the stack.

  • Because of the way it functions, like actual stacks of books, etc., it is termed a stack.
  • A pre-defined capacity abstract data type, known as a stack, allows it to hold components of a specific size.
  • It's a data structure where elements are inserted and removed in a specific order, which may be FILO or LIFO.

How Does a Stack Work?

Stack in data structure utilizes the pattern of LIFO. The stack has a size of five since it contains five memory blocks, as seen in the image below.

Assume for the moment that we wish to store the items in an empty stack. As you can see below, we have taken a size five stack and are adding items to it one at a time until the stack is filled.

Since the size of our stack is five, we can see that in the circumstances mentioned above, while we were adding a new element to the stack, the stack filled up from the bottom to the top.

The other end of the stack is closed when we execute the delete operation, thus there is only one path to enter and exit. According to the LIFO pattern, the value inserted first will be deleted last. Since the value 5 was input first in the example above, it won't be removed until all other items have been removed.

Common Operations of the Stack in Data Structure

Several operations are carried out on the stack. Some of the common ones are detailed below:

  1. push(): The process of adding an element to a stack is referred to as a push. The overflow condition happens when the stack is full.
  2. pop(): The process of removing an element from the stack is referred to as a pop. An underflow state occurs when the stack is empty, which indicates that there is not a single element in the stack.
  3. isEmpty(): This function ascertains if the stack is empty.
  4. isFull(): This function ascertains whether the stack is full.peek(): It gives back the element at the specified location.
  5. count(): This function gives back the total number of items that are in a stack.
  6. alter(): Modifies the element at the specified location.
  7. display(): It outputs every element in the stack that is accessible.


1. The Push() Operation

This is how the push() operation works:

  • We determine whether a stack is full before adding an element to it.
  • The overflow condition happens when we attempt to add an element to a stack and the stack is already full.
  • To ensure that a stack is empty when it is first created, the value of the top is set to -1.
  • When a new element is pushed into a stack, the top value is increased first (top=top+1), and the element is then positioned at the new top position.
  • We'll keep adding pieces until the stack reaches its maximum size.

The Push Algorithm

begin

 if stack is full

    return

 endif

else  

 increment top

 stack[top] assign value

end else

end procedure

2. The POP () Operation

The POP operation typically follows the following steps:

  • First, we make sure the stack is empty before removing the element from it.
  • The underflow situation happens if we attempt to remove the piece from the empty stack.
  • We first access the element that is pointed at the top of the stack if it is not empty.
  • Following the pop operation, the top is decreased by 1, meaning that top=top-1.

The POP Algorithm:

begin

 if stack is empty

    return

 endif

else

 store value of stack[top]

 decrement top

 return value

end else

end procedure

Uses of  Stack in Data Structures

Stack in data structure is very essential in algorithm development. Some of the uses of the stack in the data structure are detailed here:

  1. Symbol balancing

A symbol can be balanced by using the stack. We have the following program, for instance:

int main()  

{  

   cout<<"Hello";  

   cout<<"Upgrad";  

Every program, as we all know, consists of an opening and a closing brace. The opening braces are pushed into a stack as they appear, and the closing braces are removed from the stack when they do. Consequently, the net value equals zero. Any symbol that remains in the stack indicates that a program contains some syntax.

  1. UNDO/REDO

UNDO/REDO activities can also be carried out with it. A text written in an editor would be abc, for instance, if we were to write 'a', 'b', and 'c' in it. Thus, a, ab, and abc are the three states that are kept in a stack. Two stacks would be present, one displaying the UNDO state and the other the REDO state.

The POP procedure is used when we wish to accomplish 'ab' state and perform UNDO operation.

  1. Backtracking

Let's say we need to design a route to address a maze issue. if we find out while following a certain path that we are headed in the incorrect direction. We must use the stack in data structure to start at the beginning of the path and construct a new path.

  1. Expression conversion

Another tool for expression conversion is Stack. Among the most significant uses of stack in data structure is this one. The following is a list of expression conversions:

  • Prefix to infix
  • From infix to postfix
  • From prefix to infix
  • From prefix to postfix
  • From postfix to infix
  1. Reversing a string

You can also do this with stack. For instance, we can use a stack to reverse a "UpGrad" string if that is what we want to do.

  • Before reaching the null character, we stack every character in the string.
  • Once every character has been pushed, we begin removing each one until we get to the bottom of the stack.
  1. Recursion

This indicates that the function is making another call to itself. The compiler builds a system stack, where all of the function's prior records are kept, to preserve the earlier states.

  1. Depth First Search, or DFS

This is a search method applied to a graph that makes use of the stack data structure.

  1. Memory management

Memory management is done via stack in data structure Contiguous memory blocks are used to assign memory. Since every variable is assigned in a function called stack memory, the memory is referred to as stack memory. The compiler is aware of the memory size allocated to the program. All of the function's variables are assigned to the stack memory at the time of creation. All of the variables that were allocated to the stack are released once the function has finished running.

Here's an Example of Stack Data Structure C

Below is an example of how stacks operate in C:

// C program for array implementation of stack

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a stack

struct Stack {

int top;

unsigned capacity;

int* array;

};

// function to create a stack of given capacity. It initializes size of

// stack as 0

struct Stack* createStack(unsigned capacity)

{

struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));

stack->capacity = capacity;

stack->top = -1;

stack->array = (int*)malloc(stack->capacity * sizeof(int));

return stack;

}

// Stack is full when top is equal to the last index

int isFull(struct Stack* stack)

{

return stack->top == stack->capacity - 1;

}

// Stack is empty when top is equal to -1

int isEmpty(struct Stack* stack)

{

return stack->top == -1;

}

// Function to add an item to stack. It increases top by 1

void push(struct Stack* stack, int item)

{

if (isFull(stack))

return;

stack->array[++stack->top] = item;

printf("%d pushed to stack\n", item);

}

// Function to remove an item from stack. It decreases top by 1

int pop(struct Stack* stack)

{

if (isEmpty(stack))

return INT_MIN;

return stack->array[stack->top--];

}

// Function to return the top from stack without removing it

int peek(struct Stack* stack)

{

if (isEmpty(stack))

return INT_MIN;

return stack->array[stack->top];

}

// Driver program to test above functions

int main()

{

struct Stack* stack = createStack(100);


push(stack, 10);

push(stack, 20);

push(stack, 30);


printf("%d popped from stack\n", pop(stack));


return 0;

}

Output:

The Stack Data Structure in Python

The following is an example of stack data structure in Python:

class Stack:

    def __init__(self):

        self.items = []

def is_empty(self):

        return len(self.items) == 0

def push(self, item):

        self.items.append(item)

def pop(self):

        if not self.is_empty():

            return self.items.pop()

        else:

            return "Stack is empty"

def peek(self):

        if not self.is_empty():

            return self.items[-1]

        else:

            return "Stack is empty"

def size(self):

        return len(self.items)

# Example usage

if __name__ == "__main__":

    stack = Stack()

print("Is the stack empty?", stack.is_empty())

    stack.push(1)

    stack.push(2)

    stack.push(3)

    print("Stack size:", stack.size())

    print("Top element of the stack:", stack.peek())

    print("Popping elements from the stack:")

    while not stack.is_empty():

        print(stack.pop())

    print("Is the stack empty?", stack.is_empty())

Output:

Types of Stack in Data structures

In data structures, there are mainly two types of stacks based on their implementation. They are the following:

  1. Static Stack:
  • Static stacks have a fixed size determined at the time of creation.
  • Once the stack is full, it cannot accommodate additional elements unless some elements are removed.
  • Memory allocation for a static stack is done at compile-time.
  1. Dynamic Stack:
  • Dynamic stacks can grow or shrink in size as needed.
  • Memory allocation for a dynamic stack is done at run-time using dynamic memory allocation techniques such as pointers or dynamic arrays in data structure.
  • They are more flexible compared to static stacks but may require more memory management overhead.

Conclusion

Now you will be able to define stack in data structure and explain its various aspects. As the foundation of many methods and applications, stacks are not only common in computer science but also essential knowledge for any programmer. 

Understanding the principles of stack in data structure, such as push, pop, and peek operations, as well as their Last In First Out (LIFO) nature, gives you a valuable tool for handling a variety of issues. Stacks are used in many different disciplines, such as managing function calls in programming languages, parsing expressions, and implementing backtracking algorithms.

Additionally, learning stack operations improves your ability to solve problems and aids in the creation of effective algorithms. Your programming tasks may result in more beautiful and efficient solutions if you can use stack data structures creatively.

Frequently Asked Questions:

  1. What are stack in data structure?

Stacks are linear data structures that follow the Last In, First Out (LIFO) principle, where elements are added and removed from the same end.

  1. What is the definition of a stack?

A stack is a collection of elements with two primary operations: push, which adds an element to the top, and pop, which removes the top element.

  1. What are the two types of stacks?

The two types of stacks are:

  • Static Stack: Has a fixed size determined at the beginning.
  • Dynamic Stack: Can grow or shrink in size as needed.
  1. Are stacks known as data structures?

Yes, stacks are a fundamental type of data structure commonly used in computer science and programming.

  1. What are the stacks in data structure and example?

A stack is a data structure where elements are added and removed from the top. An example is the call stack used in programming languages for function calls.

  1. Why is stack used?

Stacks are used for managing function calls, expression evaluation, backtracking algorithms, and undo mechanisms due to their LIFO behavior.

  1. What is stack and its function?

A stack is a collection of elements with push and pop operations. Its function is to maintain data in a last-in, first-out order.

  1. What is the function of a stack?

The function of a stack is to provide operations for adding elements (push) and removing elements (pop) in a Last In, First Out (LIFO) manner.

  1. What is a stack algorithm?

A stack algorithm refers to any algorithm that utilizes a stack data structure to solve a problem. Examples include postfix expression evaluation and backtracking algorithms.

Kechit Goyal

Kechit Goyal

Team Player and a Leader with a demonstrated history of working in startups. Strong engineering professional with a Bachelor of Technology (BTech…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...