Here’s a basic implementation of a custom stack using an
array in Java. This implementation includes common stack operations such as
push, pop, peek, and checking if the stack is empty or full.
Custom Stack Using Array
java
public class
CustomStackArray<E> { private Object[] stack; private int size; private static final int DEFAULT_CAPACITY
= 10; // Constructor with default capacity public CustomStackArray() { stack = new Object[DEFAULT_CAPACITY]; size = 0; } // Constructor with specified capacity public CustomStackArray(int capacity) { stack = new Object[capacity]; size = 0; } // Push an element onto the stack public void push(E element) { if (size == stack.length) { ensureCapacity(); } stack[size++] = element; } // Pop an element off the stack @SuppressWarnings("unchecked") public E pop() { if (isEmpty()) { throw new EmptyStackException(); } E element = (E) stack[--size]; stack[size] = null; // Prevent memory
leak return element; } // Peek at the top element of the stack
without removing it @SuppressWarnings("unchecked") public E peek() { if (isEmpty()) { throw new EmptyStackException(); } return (E) stack[size - 1]; } // Check if the stack is empty public boolean isEmpty() { return size == 0; } // Get the number of elements in the
stack public int size() { return size; } // Ensure capacity of the stack private void ensureCapacity() { int newCapacity = stack.length * 2; Object[] newStack = new
Object[newCapacity]; System.arraycopy(stack, 0, newStack,
0, size); stack = newStack; } // Main method for testing public static void main(String[] args) { CustomStackArray<String> stack
= new CustomStackArray<>(); stack.push("A"); stack.push("B"); stack.push("C"); System.out.println("Peek: "
+ stack.peek()); // Output: C System.out.println("Pop: "
+ stack.pop()); // Output: C System.out.println("Peek after
pop: " + stack.peek()); // Output: B System.out.println("Size: "
+ stack.size()); // Output: 2 stack.push("D"); System.out.println("Peek after
pushing D: " + stack.peek()); // Output: D System.out.println("Size: "
+ stack.size()); // Output: 3 } } |
Key Components
- Array
Storage: Uses an Object array to store the stack elements. This allows
the stack to hold elements of any type.
- Size
Tracking: Maintains the current size of the stack.
- Push
Method: Adds an element to the top of the stack and resizes the array
if necessary.
- Pop
Method: Removes and returns the top element of the stack. Throws an EmptyStackException
if the stack is empty.
- Peek
Method: Returns the top element of the stack without removing it.
Throws an EmptyStackException if the stack is empty.
- Check
if Empty: Determines if the stack has no elements.
- Ensure
Capacity: Doubles the capacity of the internal array when the stack is
full.
- Main
Method: Tests the functionality of the stack with various operations.
This implementation provides a basic but functional stack
with dynamic resizing. You can extend it with additional features or error
handling as needed.
0 Comments