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? The insertAtTail method looks correct though. Could anyone please let me know.
thanks
Advertisement
Answer
In the traverse, you need to check all nodes not until the next one is null.
so I just removed the .nextElement from the traverse and it works fine
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) { // Here 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();