javascriptdata-structures

Queue implementation as linked list: why node is not overwritten?


//create a Node class that will represent elements/nodes in the Queue
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}
//creates a Queue class to store the elements/nodes of the Queue
class Queue {
  constructor() {
    this.first = null;
    this.last = null;
    this.size = 0;
  }
  //enqueues a node
  enqueue(val) {
    let node = new Node(val);
    if (this.size === 0) {
      this.first = node;
      this.last = node;
    } else {
      this.last.next = node;
      this.last = node;
    }
    return this.size++;
  }
  //dequeues a node 
  dequeue() {
    if (!this.first) {
      return null;
    }
    let temp = this.first;
    if (this.first === this.last) {
      this.last = null;
    }
    this.first = this.first.next;
    this.size--;
    return temp.value;
  }
}

I was following an article on medium on how to implement stacks and queues with JavaScript. I was lost when it came to queues specifically the way the author implemented enqueing. On the last bits of the method "enqueue", he writes

{
   this.last.next = node;
   this.last = node;
}

Wouldn't the previous item be overwritten by this implementation? What Im i missing?


Solution

  • this.last.next will be null, there is nothing after the last item.

    this.last.next = node; creates a link from the current last node to the new item, then this.last = node; sets the current last node to the node that was just inserted. The previous last node is still in the linked list though.