Removing node from linked list how it works?

   function LinkedList() {
   this.head = null;
   this.tail = null;
  }

  function Node(value, next, prev) {
  this.value = value;
  this.next = next;
  this.prev = prev;
  }

  LinkedList.prototype.removeHead = function() {
      if (!this.head) return null;
 var val = this.head.value;
this.head = this.head.next;

 //why here is an if condition?

if (this.head) this.head.prev = null;
else this.tail = null;
return val;

};

That’s answered by the previous statement. If there is no next head, the head won’t exist. That occurs when there is only one item in the list, and you remove that one item.

In most cases, moving the next value to the head will result in there being a valid head object. All other items have a prev value that points in the direction of the head. When it is the head, there is no useful prev value, so it’s set to null.

If there isn’t a head object though, the linked list is now empty and has no head or tail reference. The head is already null which is what brought us to this situation, so the tail also needs to be set to null too.

1 Like

Thanks got it

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.