It is relatively simple to create a custom Stack class. Especially since you can just use the implementation of the LinkedList you've already created. If you do not have your custom LinkedList on hand, you can swap it out with Java's java.util.LinkedList class.
You just need to enforce that elements can only be added and removed from the front of the underlying LinkedList.
public class CustomStackExample<V> {
// create the LinkedList that will be used
// as the underlying data structure
private SingleLinkedList<V> list = new SingleLinkedList<>();
/**
* Adds an item to the stack
* @param item to be added
*/
public void push(V item) {
// insert item into front of list
list.addFirst(item);
}
/**
* Removes an item from the stack
* @return the removed item
*/
public V pop() {
try {
// retrieve, remove, and return the first item
return list.removeFirst();
} catch (NullPointerException ex) {
System.out.println("Exception" + ex);
return null;
}
}
/**
* Determines if the stack is empty
* @return true if empty, false if not empty
*/
public boolean isEmpty() {
return list.isEmpty();
}
/**
* This empties the stack
* @return void
*/
public void clear() {
// empty the linkedlist
list.clear()
}
}
Great! There's another abstract data structure in your tool belt. Notice that the only thing this CustomStackExample can really do is addFirst() and removeFirst() (as well as isEmpty() and clear()) because of this enforced behavior you now have the abstract data structure of a Stack. Now, it is time to practice!
Summary: Custom Stack Java
- This lesson creates a custom stack class in Java
- This Stack uses a LinkedList as it's underlying data structure
- In this example, the
CustomStackExampleclass has the following methods:push()pop()isEmpty()clear()