Hi All,
I have implemented a single linked list using javascript. Please find the code below:
class Node {
constructor(data) {
this.data = data;
this.nextElement = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
isEmpty() {
return this.head === null;
}
insertAtHead(data) {
const tempNode = new Node(data);
tempNode.nextElement = this.head;
this.head = tempNode;
}
traverse() {
let current = this.head;
while (current.nextElement != null) {
console.log("node data", current.data);
current = current.nextElement;
}
}
insertAtTail(data) {
const tempNode = new Node(data);
if (this.head === null) {
this.head = tempNode;
return;
}
let currentNode = this.head;
while (currentNode.nextElement != null) {
currentNode = currentNode.nextElement;
}
currentNode.nextElement = tempNode;
}
}
const linkedList = new LinkedList();
linkedList.insertAtTail(12);
linkedList.insertAtTail(23);
linkedList.insertAtTail(25);
linkedList.traverse();
But the traverse method never prints the last element. What am i missing here ? Can anybody please help me out here ?
thx