I single linked list, we set head and tail as null if the list length is 0. i.e poping the last element would make head and tail zero.
pop() {
if (!this.head) return undefined;
var current = this.head;
var newTail = current; //newTail is the previous node of current
while (current.next) {
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
//If every items is poped out i.e we have zero items then make head and tail null
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}
But in a doubly linked list why are we setting the head and tail as null for list length 1 instead of 0.
pop() {
if (!this.head) return undefined;
var poppedNode = this.tail;
if (this.length === 1) {
this.head = null;
this.tail = null;
} else {
this.tail = poppedNode.prev;
this.tail.next = null;
poppedNode.prev = null;
}
this.length--;
return poppedNode;
}
Shouldn't the above also set head and tail to null when length is zero ?
One of the differences in these two implementations is that the first checks the value of this.length before reducing it with 1, while the other does this after reducing it with 1. That explains why the first checks against 1 while the other checks against 0. But that has nothing to do with the difference between singly and doubly linked lists. It could have been the other way around.
We could harmonize the two pieces of code, so they only differ where necessary:
pop() {
if (!this.head) return undefined;
var poppedNode = this.tail;
// Specific for singly linked list:
let newTail = null;
let current = this.head;
while (current.next != null) {
newTail = current;
current = current.next;
}
this.tail = newTail;
// End of specific part
this.length--;
if (this.length === 0) {
this.head = null;
} else {
this.tail.next = null;
}
return poppedNode;
}
pop() {
if (!this.head) return undefined;
var poppedNode = this.tail;
// Specific for doubly linked list:
this.tail = this.tail.prev;
poppedNode.prev = null;
// End of specific part
this.length--;
if (this.length === 0) {
this.head = null;
} else {
this.tail.next = null;
}
return poppedNode;
}