1. Introduction
Reversing an array is a fundamental problem in computer science. While there are several methods to reverse an array, using a stack can be an intuitive and efficient approach. A stack is a Last In First Out (LIFO) data structure. In this tutorial, we’ll explore how to reverse an array in Java with the help of a stack.
2. Program Steps
1. Define a Stack class with operations: push(), pop(), and isEmpty().
2. Push each element of the input array onto the stack.
3. Pop elements from the stack and replace elements in the array to get it reversed.
4. Display the reversed array.
3. Code Program
class Stack {
private int maxSize; // Size of the stack array
private int[] stackArray; // The stack array
private int top; // Index to the top element
public Stack(int size) {
this.maxSize = size;
this.stackArray = new int[maxSize];
this.top = -1;
}
// Push an element onto the top of the stack
public void push(int value) {
if(top < maxSize - 1) {
stackArray[++top] = value;
}
}
// Remove and return the top element from the stack
public int pop() {
return stackArray[top--];
}
// Check if the stack is empty
public boolean isEmpty() {
return (top == -1);
}
}
public class ReverseArrayUsingStack {
public static void main(String[] args) {
int[] inputArray = {1, 2, 3, 4, 5};
Stack stack = new Stack(inputArray.length);
// Push each element of the array onto the stack
for (int value : inputArray) {
stack.push(value);
}
// Pop elements from the stack and overwrite the input array to reverse it
for (int i = 0; i < inputArray.length; i++) {
inputArray[i] = stack.pop();
}
System.out.print("Reversed Array: ");
for (int value : inputArray) {
System.out.print(value + " ");
}
}
}
Output:
Reversed Array: 5 4 3 2 1
4. Step By Step Explanation
1. We start by defining a generic Stack class backed by an integer array. The stack provides essential operations like push, pop, and isEmpty.
2. The stack's capacity is initialized to the size of the array to be reversed.
3. Each element from the input array is then pushed onto the stack.
4. Leveraging the Last In First Out (LIFO) property of stacks, popping elements off the stack gives them in reversed order. We use this mechanism to overwrite the input array, effectively reversing it.
5. Finally, the reversed array is displayed.
Utilizing a stack for array reversal not only provides a clear and structured solution but also underscores the versatility of the stack data structure.