I have implemented a queue using linked list. I added a enqueue and dequeue function. As per the data structure, if after using dequeue, the item after 'front' item should become front but my code is setting 3rd item on queue as front. Please look at my code and tell me what I did wrong.
class Node {
constructor(value) {
this.value = value;
this.prev = null;
}
}
class Queue {
constructor() {
this.front = null;
this.rear = null;
this.length = 0;
}
enqueue(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.front = newNode;
this.rear = newNode;
} else {
this.front.prev = this.rear;
this.rear = newNode;
}
this.length++;
return newNode;
}
dequeue() {
if (!this.front) {
return null;
}
if (this.front === this.rear) {
this.rear = null;
} else {
this.front = this.front.prev;
this.length--;
}
return this.front;
}
}
const myQueue = new Queue();
console.log('myQueue.enqueue(5) : ', myQueue.enqueue(5));
console.log('myQueue : ', myQueue);
console.log('myQueue.enqueue(6) : ', myQueue.enqueue(6));
console.log('myQueue : ', myQueue);
console.log('myQueue.enqueue(7) : ', myQueue.enqueue(7));
console.log('myQueue : ', myQueue);
console.log('myQueue.dequeue() : ', myQueue.dequeue());
console.log('myQueue : ', myQueue);
console.log('myQueue.dequeue() : ', myQueue.dequeue());
console.log('myQueue : ', myQueue);
.as-console-wrapper { max-height: 100%!important; top: 0; }