Welcome to part three of three in the stack series videos. Today we'll be looking at some source code for a very simple stack. So the source code can be found on github.com slash wm fuzzers slash data dash structures. Make sure you understood part one and two of the stack series before continuing. So you actually know how we implement a stack using a linked list. Also, if you like this video series, and the implementation of the stack data structure I'm about to present to you then please start this repository on GitHub so that others can have an easier time finding it as well.
Here we are in the stack source code. This is an implementation in the Java programming language. So the first thing you may notice is here I have an instance variable of a linked list. This is the linked list provided by Java. In fact, it's a doubly linked list provided by Java. This is a linked list they provide in their package Java dot util, they will be using today, instead of the one that I created, and the link list videos.
This is just for portability in case you want to use the stack for whatever reason. So we have two constructors, we can create an empty stack, or we can create a stack with one initial element. This is occasionally useful. First method we can get the size of the stack. So to get to do that, we return the size of the internal links list with all the elements of our stack easy. We also check if the stack is empty by checking if the size is zero.
So this next one is just push So to push an element onto the stack, we just append that element as the last element in our internal linked list. Easy enough, we can also pop an element off the stack. So to do this, we check if the stack is empty. If it is, then we throw an empty stack exception because we can't pop an element off of an empty stack. That doesn't make sense. Similarly, the same thing with peak we can't observe on top element of the stack is if the stack is empty.
And if it's not there, we can pick the last element for list. And lastly, we can return an iterator to allow the user to iterate through our stack. This iterator returns an iterator for our linked list, which support concurrent modification errors. So this was a really, really quick implementation of a stack. It's only like 50 lines of code. However, if you do have any questions, drop me a comment below and I'll try to get to you when I'm not busy.
Thank you for watching.