My solution to the coding problem to find the middle node of a LinkedList in Javascript.

Middle Node of a LinkedList

/* LinkedList node */
class Node {
    constructor(data, next) {
        this.data = data;
        this.next = next;
    }
}
function printMiddle(head) {
    if (!head) console.log("Empty List");

    let slowPtr = head;
    let fastPtr = head;

    while (fastPtr && fastPtr.next) {
        slowPtr = slowPtr.next;
        fastPtr = fastPtr.next.next;
    }
    console.log(`The middle of the list is: ${slowPtr.data}`);
}

let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
//head.next.next.next.next = new Node(5);

printMiddle(head);

Get updates?

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Verified by MonsterInsights