class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SLL {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(val) {
let newNode = new Node(val)
if (!this.head) {
this.head = newNode;
this.tail = this.head;
} else {
console.log(this.tail);
console.log(this.tail.next);
debugger
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
}
}
let x = new SLL();
x.push('Hi');
x.push('Hello');
x.push('How');
x.push('Are');
x.push('You');
x.push('Man');
Doubt:
After the 2nd push(‘Hello’), the tail is assigned with the newNode "this.tail = newNode" under else part. But in the 3rd push "push(‘How’)" how the this.tail is still referencing the this.head.
I have done console.log of both "this.tail" and "this.tail.next".The output shows fresh node. Am not able to understand how this still reference to the this.head.
Thanks for the answers!
2
Answers
Linked list implementation with Tail address pointer