Stack Data structure Implementation in Java using Array

The stack is a linear data structure that follows the LIFO (last-in-last-out) principle. In the stack, an item inserts from the top and removes it from the top.

For example, in a box, books arranged in vertical order. The book at the top removes first and the book at the bottom removes last.

stack implementation in java

Stack Comprises Four Operations

  1. Push: Insert an item into the stack.
  2. Pop: Delete an item from the top of the stack.
  3. Peek: Returns top item of the stack
  4. isEmpty: Checks empty stack.

Recommended:Queue Data Structure Implementation in Java using an Array

Let’s create stack using an array

public class Stack {
	
	int capacity;
	int array[];
	int top;
	
	public Stack(int capacity) {
		top = -1;
		this.capacity = capacity;
		array = new int[capacity];
	}
	boolean isEmpty() {
		if(top < 0)
			return true;
		return false;
	}
	public int push(int item) {
		if(top >= capacity - 1) {
			System.out.println("The stack is overflow");
			return 0;
		}else {
			this.array[++top] = item;
			return item;
		}
	}	
	public int pop() {
		if(top < 0) {
			System.out.println("Stack is underflow");
			return 0;
		}else {
			return this.array[top--]; 
		}	
	}	
	public int peek() {
		if(top > capacity - 1) {
			System.out.println("The stack is overflow");
			return 0;
		}else if(top < 0){
			System.out.println("The stack is underflow");
			return 0;
		}else {
			return this.array[top];
		}
	}	
	public static void main(String[] args) {
		Stack stack = new Stack(4);
		System.out.println(stack.push(10) + " pushed into stack");
		System.out.println(stack.push(20) + " pushed into stack");
		System.out.println(stack.push(30) + " pushed into stack");
		System.out.println(stack.push(40) + " pushed into stack");
		System.out.println(stack.pop() + " popped from the stack");
		System.out.println(stack.pop() + " popped from the stack");
		System.out.println("Peek of the stack is " + stack.peek());		
	}
}

Output

10 pushed into stack
20 pushed into stack
30 pushed into stack
40 pushed into stack
40 popped from the stack
30 popped from the stack
Peek of the stack is 20

Practical uses of stack in real world

  1. Find whether a string is a palindrome.
  2. Evaluating a given expression is valid or not.
  3. Used in recursion functions to implement algorithms like the tower of Hanoi and tree manipulations.
  4. Conversion of expressions ( prefix-infix-postfix)

Conclusion

For interviews, the stack is an important data structure concept and understanding stack implementation will help in interviews.

Recommended:

Leave A Reply

Your email address will not be published.