Stack Implementation
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order is LIFO (Last In First Out) or FILO (First In Last Out).
Operations
- Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow condition.
O(1) - Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
O(1) - Peek / Top: Returns the top element of the stack.
O(1) - isEmpty: Returns true if the stack is empty, else false.
O(1)
Visual Representation
Array Based Implementation in Java
public class StackArray {
private int[] arr;
private int top;
private int capacity;
public StackArray(int size) {
arr = new int[size];
capacity = size;
top = -1;
}
public void push(int x) {
if (top == capacity - 1) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = x;
}
public int pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return -1;
}
return arr[top--];
}
public int peek() {
if (isEmpty()) {
return -1;
}
return arr[top];
}
public boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
StackArray stack = new StackArray(5);
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element: " + stack.peek()); // 30
System.out.println("Popped: " + stack.pop()); // 30
}
}
Note: Java also provides a built-in
java.util.Stackclass and a more modernjava.util.Dequeinterface (e.g.ArrayDeque) for stack operations.