This program demonstrates how to implement a basic stack using an array. A stack is a Last In First Out (LIFO) data structure where elements are added and removed from the top.
Program Structure
- Stack Class: Contains methods for push (add), pop (remove), peek (view top element), and checking if the stack is empty.
- Main Method: Demonstrates the functionality of the stack with push, pop, and peek operations.
Java Code
public class ArrayStack {
private int[] stack;
private int top;
private int capacity;
public ArrayStack(int size) {
capacity = size;
stack = new int[capacity];
top = -1;
}
public void push(int data) {
if (top < capacity - 1) {
stack[++top] = data;
} else {
System.out.println("Stack is full");
}
}
public int pop() {
if (top >= 0) {
return stack[top--];
} else {
System.out.println("Stack is empty");
return -1;
}
}
public int peek() {
if (top >= 0) {
return stack[top];
} else {
System.out.println("Stack is empty");
return -1;
}
}
public boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println("Top element is: " + stack.peek());
System.out.println("Popped element: " + stack.pop());
System.out.println("Popped element: " + stack.pop());
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
Explanation of How the Program Works
- Stack Initialization: The constructor initializes the stack with a given capacity, setting the top index to -1 indicating the stack is empty.
- Push Operation: Adds an element to the top of the stack if it is not full.
- Pop Operation: Removes and returns the top element of the stack if it is not empty.
- Peek Operation: Returns the top element of the stack without removing it, if the stack is not empty.
- IsEmpty Operation: Checks if the stack is empty.
Key Components:
- ArrayStack Class: This class manages the stack operations. It uses an array to store the stack elements and an integer (
top
) to track the index of the top element. - Constructor: Sets up the array and initializes
top
to -1. - Push Method: Adds an element to the top of the stack.
- Pop Method: Removes an element from the top of the stack.
- Peek Method: Returns the top element of the stack without removing it.
- IsEmpty Method: Returns true if the stack is empty.
This structure is ideal for educational purposes or simple applications where the stack size is known in advance and does not need to dynamically resize.
Conclusion
This array-based implementation of a stack is straightforward and effective for demonstrating basic stack operations. It efficiently handles the fundamental operations of pushing and popping in constant time O(1), making it suitable for scenarios where quick and predictable performance is necessary.