Stack Implementation Using Array

Stack is a linear data structure that follows an order i.e LIFO(Last In First Out), where the element which is inserted at the last will come out first.

Basically, there are 4 basic operations that are performed in the stack:

  • Push: Adds an item in the stack.
  • Pop: Removes an item from the stack. The items are popped in the reversed order.
  • Peek: Returns the top element of the stack.
  • isEmpty: Returns true if the stack is empty, else false.

In this example, we’ll see how to implement stack using an array:

1. Java

public class StackImpl {
	
	int[] stackArray;
	int top;
	
	public StackImpl(int size) {
		this.stackArray = new int[size];
		this.top = -1;
	}
	
	public void push(int value) {
		top++;
		stackArray[top] = value;
	}
	
	public int pop() {
		int topValue = top;
		top--;
		return stackArray[topValue];
	}
	
	public int peak() {
		if(isEmpty()) {
			return -1;
		}
		return stackArray[top];
	}
	
	public boolean isEmpty() {
		return top == -1;
	}

}

Performing Operations:

public class StackApp {

	public static void main(String[] args) {
		StackImpl stackImpl = new StackImpl(4);
		stackImpl.push(10);
		stackImpl.push(20);
		stackImpl.push(30);
		stackImpl.push(40);

		System.out.println("Removing " + stackImpl.pop());

		System.out.println("Peak Element " + stackImpl.peak());
   }
}

Output:

Removing 40
Peak Element 30

Stack Time Complexity:

The time complexity of the operations performed on Stack totally depends on how you implemented the Stack. Based on the above implementation below is the worst time complexity.

  • Push: O(1) time
  • Pop: O(1) time
  • Peek: O(1) time
  • Size: O(1) time.

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions