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
8

Stack Implementation Using Array in Data Structures

Updated on 25/07/2024236 Views

Introduction

Efficient algorithms and software design greatly depend on data structures. Stacks are particularly notable for being simple yet versatile when solving various computational problems.

Stack is a linear data structure that follows the LIFO (Last in First Out) rule and performs all its operations. All the stack insertion and deletion operations happen only at one end of the stack from the top of that stack. Since their early days in computing, stacks have been used in various applications, such as language parsing and memory management.

Stacks can be implemented using arrays. An array is a fundamental data structure that provides simplicity and efficiency for manipulating data. In this guide, we will go through the implementation of a stack using arrays in a data structure.

Overview

Stacks form one of the fundamental data structures in computer science. Charles Leonard Hamblin, a famous mathematician, is responsible for its development during the 1950s. Since then, stacks have become central to algorithmic design and software development.

This has been further intensified by stacks through modern programming languages as well as the exponential growth of digital technologies. Arrays have reasonable memory allocation and efficient access mechanisms, making them preferable bases for stack implementation.

Throughout this guide, you'll uncover the implementation of stack using arrays. I will guide you through operations such as push, pop, and peek for implementing stacks with arrays and much more.

What Exactly are Stacks?

Stacks are fundamental data structures operating on the Last In, First Out (LIFO) principle. The last piece added to the stack is the first to be deleted. In a stack, all operations occur at one end, typically the top of the stack. This end is the sole point for inserting new elements onto the stack and removing existing elements.

The LIFO Principle of Stacks

Think of a stack as a vertical arrangement of items, much like a stack of plates in a cafeteria. When you add a new plate to the stack, it sits on top of the previous ones. Similarly, you remove a plate from the top of the stack. This analogy illustrates the LIFO principle: the last item added to the stack is the first to be removed.

Applications of Stacks

Stacks are used in a variety of applications, such as

  • Expression evaluation
  • Function call management
  • Undo mechanisms in software applications.

Stack algorithms are also used in web browser history, text editor undo feature, and backtracking algorithms.

Basic Operations of a Stack

A stack is made up of several basic operations: push(), pop(), top(), isEmpty(), and size(). Let me tell you what these mean:

push(): this inserts an element at the end of a stack just like putting another plate on top of dishes in general.

pop(): It is that function that eliminates the highest element from the array; think about picking off or lifting out a plate from stacked plates

top(): This returns the top item without removing it, such as glancing at a dish at peak level but not taking it

isEmpty(): The function isEmpty() checks if the stack is empty by returning true for no element found while false for the presence of any.

size(): Number of elements in the stack currently. Just count them as if they were plates.

Now, let's delve into the complexity analysis of stack operations:

Complexity Analysis of Stack Operations

Operation

Time Complexity

push()

O(1)

pop()

O(1)

isEmpty()

O(1)

size()

O(1)

All basic stack operations have a constant time complexity of O(1), meaning their execution time does not depend on the number of elements in the stack. This makes stacks efficient for managing data in various algorithms and applications.

Types of Stacks

Now, let's briefly touch on some types of stacks:

  • Fixed-size Stack: A stack with a predetermined maximum capacity.
  • Dynamic Stack: A stack that dynamically adjusts its size as elements are added or removed.
  • Infix to Postfix Stack: This stack converts infix expressions into postfix expressions.
  • The Expression Evaluation Stack: It evaluates postfix expressions.
  • Recursion Stack: It is the kind of stack employed in computer programs to track function calls and return control to a proper function after a function has returned.

What Is the Array Data Structure, and Why Is It Suitable for Stacks?

The array data structure is one of the most fundamental concepts in computer science, and it offers an organized way to store several elements of similar types. Arrays provide a contiguous block of memory. The contiguous block of memory means no gaps between memory locations, with all addresses running consecutively, enabling easy access and manipulation. Arrays can be accessed by their index, allowing fast access to individual elements.

Now, why is the array particularly suitable for implementing stacks?

Well, we have defined a stack as a collection of elements arranged in a specific order, where the last element added is the first one to be removed—a concept commonly referred to as Last In, First Out (LIFO). This ordering principle aligns perfectly with the capabilities of arrays.

Now, let's tie this analogy back to arrays. Arrays provide direct access to their elements through index positions. When implementing a stack using an array, you can easily add new elements to the end of the array (top of the stack) and remove elements from the same position—a seamless reflection of the LIFO principle.

For example, suppose you're building a web browser that maintains a history of visited pages. You can use an array to represent the stack of visited URLs. Each time you visit a new page, you push its URL onto the array. When you hit the "back" button, you pop the last URL from the array, effectively navigating back through the browsing history. Implementing two stacks in an array is possible.

Implementation of Stacks Using Array

Implementing a stack using arrays involves using the structure of an array to mimic the behavior of a stack data structure. Implementing two stacks using one array is feasible. Stacks can be implemented with arrays with the following operations:

1. Push Operation

When putting a stack in arrays, the "Push" operation involves adding an element to the top of the stack. In this process, you allocate memory for a new element and place it at the top of the stack. Let’s go through this procedure:

  • First, you find out where this new element will be positioned by incrementing the stack pointer to point to the next available position in the array.
  • Next, assign that index to the new element.
  • Finally, update the stack pointer to indicate a new top of the stack.

Algorithm of push Operation

begin

if top = t

stack is full

top = top + 1

stack(top) = data

End

Implementing Push operations using C programming language:

#define MAX_SIZE 100 // Maximum stack size

int stack[MAX_SIZE]; // Array to store the stack elements

int top = -1; // Initialize stack pointer

// Function to add an element to the stack.

void push(int element) {

if (top == MAX_SIZE - 1) { // Check if the stack is full

printf("Stack Overflow! Cannot push element.\n");

return;

}

top++; // Increment stack pointer

stack[top] = element; // Assign element to top of stack

printf("Element %d pushed onto the stack.\n", element);

}

In this C implementation, the push function adds an element to the top of the stack. If the stack is full, it prints a "Stack Overflow" message.

2. Pop Operation

The Pop operation in a stack removes the topmost element from the stack. It reduces the stack's size by one and returns the deleted member. If the stack is empty, attempting to pop will result in an underflow condition.

The pop operation typically involves two steps:

  • Incrementing the top variable by one whenever an item is removed from the stack.
  • Storing the topmost variable of the stack in another variable, then decrementing the top variable by one.

Algorithm for pop operation

Begin

if top = 0

stack is emptied

value = stack(top)

top== top -1

end

Implementation of pop operation using C programming language

#include <stdio.h>

#define MAX_SIZE 100 // Maximum stack size

int stack[MAX_SIZE]; // Array to store stack elements

int top = -1; // Variable to keep track of the top element of the stack

// Function to pop an element from the stack

int pop() {

if (top == -1) {

printf("Stack Underflow\n");

return -1; // If stack is empty, return -1 indicating underflow

} else {

int poppedElement = stack[top]; // Store the topmost element

top--; // Decrement the top pointer

return poppedElement; // Return the popped element

}

}

int main() {

// Push a few components on the stack.

// For example:

for (int i = 0; i < 5; i++) {

stack[++top] = i; // Increment top and add elements to the stack

}

// Pop components off the stack and print them.

// For example:

printf("Popped elements: ");

while (top != -1) {

printf("%d ", pop()); // Pop elements until stack is empty

}

return 0;

}

Output:

Popped elements: 4 3 2 1 0

This demonstrates how the pop operation is implemented using arrays to mimic a stack data structure in C.

3. Peek Operation

Peek operation, allows you to return the top element of the stack without removing it, using arrays. Underflow problems may occur if you attempt to return the topmost element while the stack is already empty.

Algorithm of the Peek operation

Begin

if top = -1

stack is empty

data = stack[top]

return data

End

Implementation of peek operation using C programming languages

This code develops a data structure for Stack using Arrays and then gives implementation for checking if Stack is empty and peeking at its topmost element as well as pushing elements into and peeking at them in Stack.

#include <stdio.h>

#define MAX_SIZE 100 // Maximum stack size

int stack[MAX_SIZE]; // Declaring stack array

int top = -1; // Variable to keep track of the top element of the stack

// Function to check if the stack is empty

int isEmpty() {

return top == -1;

}

// Function to peek at the top component of your stack

int peek() {

// look at the stack to see if it is empty

if (isEmpty()) {

printf("Stack is empty. Cannot peek.\n");

return -1; // Returning -1 to signify an error

} else {

return stack[top]; // Take it back to the top component of the stack

}

}

int main() {

// Example usage

push(1);

push(2);

push(3);

printf("Top element of the stack: %d\n", peek()); // Should print 3

return 0;

}

Output:

Top element of the stack: 3

The Benefits and Drawbacks of Stack Implementation Using Array

Benefits

Drawbacks

Memory Efficiency: Memory usage is optimized with arrays since they use blocks of contiguous memory; thus no additional pointers or node structures are required.

Fixed Size Limitation: The size of an array is determined beforehand and cannot be changed dynamically thus leading to potential overflow/underflow situations when size exceeds its capacity or lesser than required.

Familiarity: Arrays are basic in programming as data structures and many developers are already familiar with them, which makes it easier to comprehend, implement and maintain.

Limited Flexibility: This is because arrays do not resize dynamically thereby making insertion, deletion or resizing operations tedious and possibly inefficient especially when the size of a stack keeps on changing.

Time Efficiency: Array-based stack operations that involve accessing elements, checking if a stack is empty or looking at its topmost elements in general take less time due to direct indexing and predictable memory access patterns.

Wastage of Space: If the allocated array size is significantly larger than the actual number of elements in the stack, it may lead to wastage of memory thus causing inefficiency in terms of overall memory usage.

Inefficient for Dynamic Data: When arrays are used to build dynamic data structures that require frequent resizing or reorganization operations; resizing can be expensive considering the time and space complexity.

Conclusion

In conclusion, stack implementation using arrays offers a robust solution for managing data in various computational tasks. While arrays provide efficiency and simplicity in accessing elements, their fixed size and time efficiency of array-based stack operations make them invaluable in numerous applications.

Stacks play a pivotal role in streamlining operations and optimizing resource usage. They are used in web browser history management, function call tracking in software development, and much more.

We hope this tutorial helped you understand the implementation of stacks using arrays. Now, go ahead and do it on your own like a pro.

FAQs

  1. How stacks are implemented using arrays?

Stacks are implemented using arrays by utilizing the Last-In-First-Out (LIFO) principle, where elements are added and removed from the end of the array, simulating the behavior of a stack.

  1. What is an array and linked implementation of the stack?

Array implementation of stacks uses a fixed-size array to store elements. In contrast, the linked implementation uses a linked list structure where each element points to the next one, offering flexibility in size.

  1. What is the value of the top in the stack when implemented using an array?

The value of “top” in a stack implemented using an array represents the index of the topmost element in the array.

  1. How to implement a stack using arrays in Java?

Java array-based stack implementation involves creating a class that contains methods to push, pop, and peek elements in the array and also managing the "top" pointer. What is the implementation of stacks?

An implementation of a stack is concerned with the underlying data structure as well as actions performed upon it like push, pop, and peek.

  1. How do you implement an array?

Implementing an array involves declaring a variable of the required type followed by square brackets containing the size of the array thus: int[] myArray = new int[size];

  1. What is array-based implementation?

The array-based implementation for stacks employs an array as its fundamental data structure for storage and efficient execution of various operations on stacks.

  1. Which implementation is best for stack?

In case one wants to implement a stack, then this will depend on certain factors such as specific peculiarities of application requirements, patterns for expected use, performance concerns, and so forth.

  1. What is a good implementation of a stack?

A good implementation would have to be fast, easily understandable, and secure enough. It should guarantee proper execution in all these cases such as pushing, popping, peeking, or isEmpty.

Abhimita Debnath

Abhimita Debnath

Abhimita Debnath is one of the students in UpGrad Big Data Engineering program with BITS Pilani. She's a Senior Software Engineer in Infosys. She…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...