Logo

dev-resources.site

for different kinds of informations.

Implementation of Stack Using Array

Published at
11/17/2023
Categories
java
dsa
programming
stack
Author
believer15
Categories
4 categories in total
java
open
dsa
open
programming
open
stack
open
Author
10 person written this
believer15
open
Implementation of Stack Using Array

In this Article, We will learn how we can Implementation our own Stack and Use it. I'm using java but you can use whatever language you comfortable with.

Prerequisites :- You must be familiar with classes and object to implement stack.

Before Moving to Implementation, Let's have look to this What is tack? What Operation we can perform? for better understanding.

*How Stack Works ? *
As we know stack is linear data structure and follows the particular order to perform operations which standardize on LIFO principle.
Whatever the stack does it maintain the discipline to perform operation.

for example : In array we can access data using index in O(1) operation but in stack we can't do. So here we follow certain order to perform this task in stack in O(n).
Keeping this thing in mind we move to implementation part.

List of the function

Brief introduction which we're going to implement

push(): When we insert an element in a stack then the operation is known as a push. If the stack is full then the overflow condition occurs.

pop(): When we delete an element from the stack, the operation is known as a pop. If the stack is empty means that no element exists in the stack, this state is known as an underflow state.

isEmpty(): It determines whether the stack is empty or not.

isFull(): It determines whether the stack is full or not.'

peek(): It returns the element at the given position.

count(): It returns the total number of elements available in a stack.

display(): It prints all the elements available in the stack.

Implementation Using Array

Initialize the class
Declare variable array as 'arr' and integer with index 0;
Note:- Behind the scene, Array work as stack. So, don't be amazed. Just know these thing.

public static class Stack {
        int[] arr = new int[5];
        int idx = 0;
}

Enter fullscreen mode Exit fullscreen mode

Defining Methods in class Stack

Push Method

1- The push method takes an integer parameter x, representing the element to be pushed onto the stack.
2- It checks if the stack is full by calling a method isFull().
3- If the stack is full, it prints "Stack is Full" to the console and returns, indicating that the push operation cannot be performed.
4- If the stack is not full, it assigns the value of x to the next available position in the stack array (arr) at index idx.
5- The index idx is then incremented, possibly pointing to the next available position for the next push operation.

void push(int x){
     if(isFull()){
         System.out.println("Stack is Full");
         return;
     }
     arr[idx] = x;
     idx++;
}

Enter fullscreen mode Exit fullscreen mode

Peek Method

1- The peek method takes no parameters but uses the instance variable idx to determine the top of the stack.
2- It checks if the stack is empty by verifying if the index idx is equal to 0.
3- If the stack is empty, it prints "Stack Empty" to the console and returns -1, indicating that there is no valid element to peek.
4- If the stack is not empty, it returns the value of the element at the top of the stack. The index idx-1 is used because the top element is at one position below the current value of idx.

int peek(){
    if(idx == 0){
        System.out.println("Stack Empty");
        return -1;
    }
    return arr[idx-1];
}
Enter fullscreen mode Exit fullscreen mode

Pop Method

1- The pop method is used to remove and return the element at the top of the stack.
2- It checks if the stack is empty by verifying if the index idx is equal to 0.
3- If the stack is empty, it prints "Stack is Empty" to the console and returns -1, indicating that there is no valid element to pop.
4- If the stack is not empty:

  • It retrieves the value of the element at the top of the stack (arr[idx - 1]) and stores it in a variable named top.

  • Sets the element at the top of the stack to 0, essentially removing it from the stack.

  • Decrements the index idx to point to the next available position in the stack.

  • Returns the value of the removed element (top).

int pop() {
  if(idx == 0){
      System.out.println("Stack is Empty");
      return -1;
  }
  int top = arr[idx -1];
  arr[idx-1] = 0;
  idx--;
  return top;
}
Enter fullscreen mode Exit fullscreen mode

Display Method

1- The display method is responsible for printing the contents of the stack to the console.
2- It uses a for loop to iterate over the elements of the stack array (arr) from index 0 to idx-1.
3- Inside the loop, it prints each element followed by a space.
4- After the loop, it prints a newline character (System.out.println()) to move to the next line in the console.

void display(){
     for(int i = 0; i <= idx-1; i++){
         System.out.print(arr[i] + " ");
     }
     System.out.println();
}
Enter fullscreen mode Exit fullscreen mode

isEmpty Method

IsEmpty return boolean.

boolean isEmpty(){
   if(idx == 0) return true;
   else return false;
}
Enter fullscreen mode Exit fullscreen mode

Size/Count Method

int size() {
    return idx;
}
Enter fullscreen mode Exit fullscreen mode

isFull Method

boolean isFull(){
   if(idx == arr.length) return true;
   else return false;
}
Enter fullscreen mode Exit fullscreen mode
stack Article's
30 articles in total
Favicon
Stack Developer Web
Favicon
Whats your TECH stack ?? How did you get into that??
Favicon
Building a Stack Implementation in Java: Mastering Data Structure Fundamentals.
Favicon
Pattern 7: Stack
Favicon
Stacks: 50 Leetcode Questions
Favicon
Why Is Stack Memory Faster Than Heap Memory? Hereโ€™s What You Need to Know!
Favicon
Stack: Concepts and Applications โ€” Java
Favicon
Top 7 Reasons to Hire a MERN Stack Development Company for Scalable Web Solutions
Favicon
Maximum swap
Favicon
Comprehensive ๐—š๐˜‚๐—ถ๐—ฑ๐—ฒ ๐˜๐—ผ ๐—ฆ๐˜๐—ฎ๐—ฐ๐—ธ ๐——๐—ฎ๐˜๐—ฎ ๐—ฆ๐˜๐—ฟ๐˜‚๐—ฐ๐˜๐˜‚๐—ฟ๐—ฒ: ๐—œ๐—บ๐—ฝ๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป, ๐—ข๐—ฝ๐—ฒ๐—ฟ๐—ฎ๐˜๐—ถ๐—ผ๐—ป๐˜€, ๐—ฎ๐—ป๐—ฑ ๐—ฃ๐—ฟ๐—ผ๐—ฏ๐—น๐—ฒ๐—บ-๐—ฆ๐—ผ๐—น๐˜ƒ๐—ถ๐—ป๐—ด
Favicon
Understanding Stack as an Abstract Data Type
Favicon
Heap vs Stack: como o Java gerencia o que deve ser lembrado ou esquecido
Favicon
Factors to consider in choosing a tech stack for a project
Favicon
stack in PyTorch
Favicon
Becoming a Full Stack Developer: A Step-by-Step Guide
Favicon
Full Stack Development: A Comprehensive Guide
Favicon
The Complete Guide to Full Stack Development: Essential Skills and Strategies
Favicon
Stack & Heap
Favicon
Stacks in Action: A Dive into the Concept and Implementation
Favicon
An ode to Stacks and Pointers in Go!
Favicon
Queue and Stack Essentials: A Python Programmer's Guide
Favicon
Navigating the Seas of Web Development
Favicon
Stack are not Queue
Favicon
Solving DSA Problems. HackerRank: Balanced Brackets
Favicon
Understanding Stack Memory and Heap Space inย Java.
Favicon
Join Our Stack Programming Community!
Favicon
Understanding the Stack Data Structure: A Java Implementation
Favicon
A Brief Look At Spotify's Tech Stack
Favicon
Implementation of Stack Using Array
Favicon
Detect what calls your Node.js code

Featured ones: