Monday, May 2, 2022

Question 41: Implement a stack using array

You need to implement Stack using array. You need to write push and pop methods to demonstrate Stack behavior(Last In First Out).


Stack is abstract data type that demonstrates Last in first out (LIFO) behavior. We will implement the same behavior using Array.

Although java provides an implementation for all abstract data types such as Stack,Queue and LinkedList but it is always a good idea to understand basic data structures and implement them yourself.

Please note that Array's implementation of Stack is not dynamic in nature. You can implement Stack through a linked list for dynamic behavior.

Stack basic operations

Stack supports the following basic operations.

push: Push the element to the top of the Stack. This operation will increase the size of the stack by 1.
pop: Remove the element from the top of the Stack and returns the deleted Object. This operation will decrease the size of the stack by 1.
isEmpty: Check if stack is empty or not.
isFull: Check if stack is full or not.
peek: Returns the top element from the stack without removing it.

Please note that the time complexity  of all the above operations is constant i.e. O(1)

Stack implementation using Array

public class StackCustom { int size; int arr[]; int top; StackCustom(int size) { this.size = size; this.arr = new int[size]; = -1; } public void push(int pushedElement) { if (!isFull()) { top++; arr[top] = pushedElement; System.out.println("Pushed element:" + pushedElement); } else { System.out.println("Stack is full !"); } } public int pop() { if (!isEmpty()) { int returnedTop = top; top--; System.out.println("Popped element :" + arr[returnedTop]); return arr[returnedTop]; } else { System.out.println("Stack is empty !"); return -1; } } public int peek() { if(!this.isEmpty()) return arr[top]; else { System.out.println("Stack is Empty"); return -1; } } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (size - 1 == top); } public static void main(String[] args) { StackCustom StackCustom = new StackCustom(10); StackCustom.pop(); System.out.println("================="); StackCustom.push(10); StackCustom.push(30); StackCustom.push(50); StackCustom.push(40); System.out.println("================="); StackCustom.pop(); StackCustom.pop(); StackCustom.pop(); System.out.println("================="); } }

Stack is empty ! ================= Pushed element:10 Pushed element:30 Pushed element:50 Pushed element:40 ================= Popped element :40 Popped element :50 Popped element :30 =================

Don't miss the next article! 
Be the first to be notified when a new article or Kubernetes experiment is published.                            

   Share This

You may also like

Kubernetes AWS Java Coding Question
Microservices Core Java Python
Spring Framework AI/MLSpring Boot