Data Structures: Linked List Queue in TypeScript

Unraveling the Mysteries of the Linked List Queue in TypeScript

Introduction

Enough foreplay. Let's get into it. The Linked List Queue in TypeScript

What's a Queue?

Before we leap into the thick of it, let's chat about queues. Imagine you're in line for a roller coaster. The first one in line is the first to ride. That's a queue in real life: First In, First Out (FIFO). In programming, it's pretty much the same. Data goes in, waits its turn, and then it's off on its adventure.

Linked List Queue: The Basics

Now, merge this queue concept with a linked list. A linked list is like a treasure hunt where each clue points to the next. Each element (we call them 'nodes') holds data and a reference to the next node. It's like a chain of data pearls! But as in the Linked List Stack article, we are going to sort of cheat. We will be using the Linked List With Tail. Importing that, so refer to that post if you aren't aware of how it works.

The Structure of a Linked List Queue

Let's roll up our sleeves and dissect this creature.

Node Class

As mentioned earlier, we are cheating. The node class will be handled already in the linked list with tail. So refer to the Linked List With Tail article.

Queue Class

Next, the Queue itself.


class LinkedListQueue {
	list: LinkedListWithTail

	constructor() {
		this.list = new LinkedListWithTail()
	}

    // Methods will go here
}

What can our Linked List Queue do?

Enqueue: Join the Queue


enqueue(element: any): void {
		this.list.append(element)
	}

enqueue is like saying, Hey, join the line! New node comes in, stands at the end of the line.

Dequeue: Time to Leave the Queue


dequeue() {
	return this.list.removeFromFront()
}

dequeue is when the node at the front leaves the queue. Bye-bye, node! Enjoy the ride!

Peek:


peek() {
	return this.list.head?.value
}

peek lets you sneak a peek at the first item without removing it. Like peeking into a gift box!

IsEmpty:


isEmpty() {
	return this.list.isEmpty()
}

isEmpty tells you if the queue is empty. No one in line? Time for a coffee break!

getSize: How Long is the Line?


getSize() {
	return this.list.getSize()
}

getSize tells you how many are in the queue. Handy for knowing if you're in for a long wait.

print: show me stuff


print() {
	this.list.print()
}


Why Use a Linked List Queue?

So, why go for a linked list queue? Flexibility and efficiency! Adding and removing are a breeze, no need to shuffle things around like in an array. Plus, it's dynamic; it grows and shrinks as needed.

Conclusion

There you have it, adventurers! The Linked List Queue in TypeScript. A nifty, efficient data structure, perfect for when you need order and simplicity. So, next time you're coding up a storm in TypeScript, remember this little gem.