DEV Community

Ujjwal Sinha
Ujjwal Sinha

Posted on

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

Top comments (0)