Data Structures and How To Build It From Scratch (Queue) #5
A queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order.
We will make one class called Queue, and it will contain three main methods: peek(), enqueue(), and dequeue().
Just like Stack, we gonna use LinkedList to implement Queue.
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 first = null, last = null, and length = 0.
Next, we will write our first method called peek(). Peek is a method to return the first data from a queue.
The next method is enqueue. Enqueue will insert data into the last of a queue. We create a variable called newNode to hold a new node. After that, we make a condition that if the length of newNode is still 0, we are going to set this. This comes first, then that.final to newNodeOtherwise, we’ll do it.this.last and last.next to newNodeLast, we have to increment the queue length and return this.
Finally, our last method is dequeue. Dequeue will remove the first data in the queue. First, we check if this.first is not null. After that, we check if this.first is equal to this. Last, we set this to null. Then we write this. first as this. first Next, decrement this.length and return this.
This is the full code of Queue.
I’ll see you on Data Structures and How To Build It From Scratch (Tree) #6.