Data Structures and How To Build It From Scratch (Stack) #4
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO (Last In First Out) or FILO (First In Last Out).
We will make one class called Stack and it will contain three main methods: peek(), push(), and pop().
As we learned about LinkedList before, we are going to use LinkedList to implement Stack.
The first thing to do is to make a class called Node to make a new node.
After that, we make a class called Stack and its constructor. As we initiate the class Stack, we set top = null, bottom = null, and length = 0.
Next, we will write our first method called peek(). A peek is a method to return to the top of the stack. It’s as simple as returning this.top.
The next method is push(). Push will add data to the top of the stack. We create a variable called newNode to hold a new node. After that, we make a condition. If this.length is zero, it means this stack doesn’t have any values. So we’re going to do that.top to newNode, as well as this.bottom to newNodeAlso, we create a variable called holdingPointer to store this. set this upSet this to top to newNode.top, next to the pointer.The last step is to increment this.length.
Finally, our last method is pop(). Pop will remove a data point from the top of the stack. The first step is that we have to make sure if this.top exists or not. After that, we set this.top. next to this.top and subtract this.length
And that’s it. It’s pretty simple, right? XD.
This is the full code of Stack.
I’ll see you on Data Structures and How To Build It From Scratch (Queue) #5.