Member-only story
A stack is an essential data structure in the world of computer science. Here is a simple implementation of it using an ArrayList as the underlying data structure.
Just like a stack of rocks, you can only remove aka pop()
, elements from the top of the stack, and add akapush()
, elements to the bottom of the stack.
No trick Jenga-style moves allowed!
You can however, peek()
at the top of the stack without removing it.
In Java, there is a util
library that contains “pre-made” Stacks that you can use without having to implement yourself.
However, if you are trying to learn data structures and algorithms, it is always recommend to try and create your own stack, to deepen your understanding.
Implementation
Here’s Java code that implements the stack interface:
public class Stack<E extends Comparable<E> > {
List<E> elements = new ArrayList<>();
public void push(E e){
elements.add(e);
}
public E pop() throws Exception {
if (elements.isEmpty()) {
throw new Exception("Cannot pop empty stack");
}
final int lastElemIndex = elements.size() - 1;
final E result = elements.get(lastElemIndex);
elements.remove(lastElemIndex);
return result;
}
public int size() {
return elements.size();
}
public boolean isEmpty() {
return elements.isEmpty();
}
public E peek() {
return elements.get(elements.size()-1);
}
}
If you have any questions or concerns, feel free to leave a comment and I will get back to you.