Stacks in Java
A stack is a linear data structure that follows the Last In First Out(LIFO) principle. This means the last element inserted inside the stack is the first to be removed. Think of a stack as a pile of plates. You would typically grab the container that is on the top of the pile. Another example of a stack is the game Tower of Hanoi.
Uses Cases
Web Browser Back Button
Text Editors' Undo Function
Function Call Stack
Expression Evaluation
Backtracking Algorithms
Reverse Polish Notation
Browser History
Syntax Checker
Implementation and Methods of a Stack with An Array
//Space Complexity O(n)
public class Stack {
//the three fields needed
private int maxSize;
private int top;
private int[] stackArray;
//constructor for initializing a new stack
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
// O(1) added a new element to the top of the stack
public void push(int val) {
if(isFull()) {
System.out.println("StackOverflowException");
}
stackArray[++top] = val;
}
// O(1) removes the top element from the stack, making
//the element below it the new top element
public int pop() {
if(isEmpty()) {
System.out.println("Stack is empty")
return -1;
}
return stackArray[top--];
}
// O(1)
public int peek() {
if(isEmpty()) {
System.out.println("Stack is empty.");
return -1;
}
return stackArray[top];
}
// O(1)
public boolean isEmpty() {
return (top == -1);
}
// O(1)
public boolean isFull() {
return (top == maxSize - 1);
}
// O(1)
public int size() {
return top + 1;
}
}
The basic methods are:
Push: add an element to the top of a stack
Pop: removes an element from the top of a stack
isEmpty: checks if the stack is empty
isFull: checks if the stack is full
Peek: Get the value of the top element without removing it
The time complexity for all the methods are O(1) when implemented with an array.
Additional Details
Stacks can be implemented with other data structures like Linked List and Deque(Double-ended Queue)
Most programming languages provide built-in support for stacks through libraries or stand data structures