The Stack is a fundamental data structure. It follows the last in first out principle (LIFO). This means that the most recent element added to the stack is the first to be removed, we can explain this with the good old stack of plates example. If you have a stack of plates and want to remove one plate, you pick from the top, that is the most recent plate.
Our Stack class
The class would have an array field, so our stack elements are saved in an array, we would also have a size field, that keeps track of capacity of our array.
public class CoolStack {
private int [] items;
private int count;
public CoolStack(int size){
items = new int[size];
count = 0;
}
}
Now we have our structure, its now time to implement methods
Check if Stack is empty
This method helps prevent exceptions being thrown by checking if the stack is empty, we should do this before removing an element from the stack.
public boolean isEmpty(){
return count == 0;
}
Push
This method enables us to add elements to the top of the stack. We have to be careful in case the stack is full, adding another element to it would lead to an exception (StackOverflow Exception). After pushing the element, we increment the counter.
public void push(int item){
if(count == items.length)
throw new StackOverflowError();
items[count] = item;
count++;
}
Pop
This allows us to remove an element from the stack, we have to remove the most recently added element (the one on top of the stack). After removing we decrement the counter.
public int pop(){
if(isEmpty())
throw new IllegalStateException();
int item = items[count - 1];
count--;
return item;
}
Peek
As the name suggests, we take a peek at the element at the top of the stack, we don't remove the element, nor do we decrement the count. We just check the top of the stack and see what's in there.
public int peek(){
if(isEmpty())
throw new IllegalStateException();
return items[count - 1];
}
Conclusion
In this blog post, we've covered the essential steps for building a simple stack class, including defining the class, implementing basic stack operations, and testing the class. Feel free to explore additional features and enhancements to further expand the capabilities of your custom stack class. Happy coding!