Stack is a basic data structure which could be compared as logical stack in real world scenario. A stack is a limited access data structure - elements can be added and removed from the stack only at the top.
There are mainly 3 functions that are performed on the stack:
Stack always perform Last In First Out(LIFO) operation. Consider a stack with elemnts [1, 2, 3, 4, 5]. 5 being at top. Will perform operation on stack
Implementation details: One of the basic ways to create a stack is using arrays.
public class Stack {
private int array[];
private int currentIndex = -1;
public Stack(int size) {
array = new int[size];
}
public void push(int number) {
if (currentIndex >= array.length) {
//throw exception
return;
}
array[++currentIndex] = number;
}
public int pop() {
if (isEmpty()) {
//throw custom exception
throw new ArrayIndexOutOfBoundsException("stack is empty");
}
return array[currentIndex--];
}
public int peek() {
if (isEmpty()) {
//throw custom exception
throw new ArrayIndexOutOfBoundsException("stack is empty");
}
return array[currentIndex];
}
public boolean isEmpty() {
return currentIndex == -1;
}
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(4);
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Output is:
5
4
3
java.lang.ArrayIndexOutOfBoundsException: stack is empty