Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

middle node of linked list javascript

This is very easy solution to find Middle Node of linked list in javascript. The approach is simple, move slow pointer 1 step and fast pointer 2 steps. When fast pointer reaches end of the list, slow pointer will be half of the list and return slow pointer.



Javascript program to find middle node of linked list


var middleNode = function(head) {
    let slow = head, fast = head;
    
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
 
    return slow;
};


Time Complexity : O(n)
Space Complexity : O(1)




This post first appeared on CodeforJS, please read the originial post: here

Share the post

middle node of linked list javascript

×

Subscribe to Codeforjs

Get updates delivered right to your inbox!

Thank you for your subscription

×