Introduction
Stacks are a key component of computer science that adhere to the Last-In-First-Out (LIFO) principle. In the context of a stack data structure, components are both inserted and deleted from a singular end, sometimes referred to as the "top" of the stack. This article delves into the theoretical framework of stacks, their practical uses, and presents a comprehensive implementation of stacks in the Java programming language utilizing arrays.
Understanding the Stack Abstract Data Type (ADT)
A stack supports two primary operations:
Additionally, stack ADT can include the following methods:
Array-Based Stack Implementation in Java
A stack can be implemented using an array. Here's how you can implement the stack ADT in Java:
import java.util.EmptyStackException;
public class ArrayStack<E> implements Stack<E> {
private static final int CAPACITY = 1000; // Default capacity of the stack
private E[] data;
private int top = -1; // Index of the top element in the stack
public ArrayStack() {
this(CAPACITY); // Initialize with default capacity
}
public ArrayStack(int capacity) {
data = (E[]) new Object[capacity]; // Create an array of specified capacity
}
public int size() {
return top + 1; // Number of elements in the stack
}
public boolean isEmpty() {
return top == -1; // Check if the stack is empty
}
public void push(E element) throws FullStackException {
if (size() == data.length) {
throw new FullStackException("Stack is full");
}
data[++top] = element; // Add element to the top of the stack
}
public E pop() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException();
}
E element = data[top]; // Get the top element
data[top--] = null; // Remove the top element
return element;
}
public E top() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException();
}
return data[top]; // Return the top element without removing it
}
}
Example Usage of ArrayStack
public class Main {
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<>();
stack.push(5);
stack.push(10);
stack.push(15);
System.out.println("Top element: " + stack.top()); // Output: 15
System.out.println("Stack size: " + stack.size()); // Output: 3
stack.pop();
System.out.println("Stack size after pop: " + stack.size()); // Output: 2
}
}
Conclusion
A comprehensive grasp of stacks and their implementations is essential for a wide range of computer science applications. The present article offers a comprehensive examination of the stack abstract data type (ADT), including an analysis of its methods and a demonstration of its practical implementation in the Java programming language utilizing arrays. Stacks exhibit versatility and find applications in various domains, including algorithms, expression parsing, function call management, and other related areas. Gaining proficiency in this foundational data format provides the opportunity to effectively address intricate situations.
Posted using Honouree