Intro
Last time, we learned what a Queue is and set it up.
Today, we learn how to enqueue / add a new node to the end of the Queue.
Starter Code ▶️
We start with the code from the last part.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.length = 0;
this.start = null;
this.end = null;
}
}
Thoughts 💭
First, we should think about the constraints and possibilities:
If the Queue is empty:
- create a new node
- set the new node as start and end
- increase the queue's length by 1
- return the new node
All remaining cases:
- create a new node
- set the new node as the end's next node
- set the new node as the new end
- increase the queue's length by 1
- return the new node
Example
// current queue:
A (start) ==> B (end)
// desired queue:
A (start) ==> B ==> C (end)
Steps:
// current queue:
A (start) ==> B (end)
// set the new node as the end's next node
A (start) ==> B (end) ==> C
// set the new node as the new end
A (start) ==> B ==> C (end)
// desired queue:
A (start) ==> B ==> C (end)
✅
Implementation 📝
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Queue {
constructor() {
this.length = 0;
this.start = null;
this.end = null;
}
enqueue(value) {
// create a new node
const newNode = new Node(value);
if (!this.length) {
// set the new node as start and end
this.start = newNode;
this.end = newNode;
} else {
// set the new node as the end's next node
this.end.next = newNode;
// set the new node as the new end
this.end = newNode;
}
// increase the queue's length by 1
this.length += 1;
// return the new node
return newNode;
}
}
Result
Let's have a look how to use the enqueue
method and its results.
const newQueue = new Queue();
// empty queue
console.log(newQueue);
// Queue { length: 0, start: null, end: null }
console.log(newQueue.enqueue("new A"));
// Node { value: 'new A', next: null }
// queue with 1 node
console.log(newQueue);
// Queue {
// length: 1,
// start: Node { value: 'new A', next: null },
// end: Node { value: 'new A', next: null }
// }
console.log(newQueue.enqueue("new B"));
// Node { value: 'new B', next: null }
// queue with 2 nodes
console.log(newQueue);
// Queue {
// length: 2,
// start: Node { value: 'new A', next: Node { value: 'new B', next: null } },
// end: Node { value: 'new B', next: null }
// }
✅
Next Part ➡️
We will implement our next method to dequeue
the first node.
Don't miss interesting stuff, subscribe!
Questions ❔
- Do you see some similarities to the Singly Linked List or Doubly Linked List?
Top comments (0)