A fully featured generic Stack implementation in Java using a singly linked list.
This stack follows the LIFO (Last In, First Out) principle and supports common operations as well as useful utility methods for flexibility and convenience.
- Generic: works with any type (
Stack<T>) - Core stack operations:
push(T item)— push an element onto the stacktop()— remove and return the top element (equivalent topop)peek()— return (without removing) the top elementisEmpty()— check if the stack is emptysize()— number of elements in the stack
- Iterable: supports iteration from top to bottom with enhanced for-loops
- Utility methods:
clear()— empties the stackcontains(T item)— checks if the stack contains a given element (supportsnull)popAll(Consumer<T> action)— pops all elements applying an action to eachtoArray()— returns an array of elements in LIFO orderclone()— creates a shallow copy of the stackreverse()— reverses the order of elements in the stack
- Properly overrides
equals(Object)andhashCode() - Throws
NoSuchElementExceptionwhen popping or peeking from an empty stack - Well documented with Javadoc comments
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.peek()); // Output: 30
while (!stack.isEmpty()) {
System.out.println(stack.top()); // Pops and prints: 30, 20, 10
}The implementation comes with comprehensive unit tests using JUnit 5.
To run the tests:
- Ensure you have JUnit 5 set up in your build system (Maven, Gradle, or your IDE).
- Run
StackTest.javaas a JUnit test suite. - All tests cover normal operations, edge cases (empty stack,
nullelements), and utility methods.
- Internally implemented with a singly linked list (
Node<T>) for dynamic size and efficient push/pop. - Iterator returns elements from top to bottom.
- Supports
nullelements safely in methods likecontains(),equals(), andhashCode(). clone()creates a shallow copy preserving element order.reverse()modifies the stack in-place reversing the element order.
Stack<String> names = new Stack<>();
names.push("Alice");
names.push("Bob");
names.push("Charlie");
names.reverse();
for (String name : names) {
System.out.println(name);
}
// Prints:
// Alice
// Bob
// Charlietrigologiaa
This project is released under the MIT License. Feel free to use, modify, and distribute.
For questions or contributions, please open an issue or contact the author.