LeetCode Problem - Link

A supposedly stepped-up difficult problem in easy mode on the Explore Course I was doing. It isn't tough if you know how to traverse a Linked List.


Sequential Solution

I first traversed once to find out the length of the LinkedList, next, I traversed again to find out the node at the midpoint of the linked list after calculating the midpoint.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function (head) {
    // One loop to find the length of the LinkedList
    var curr = head;
    var length = 0;
    while (curr !== null) {
        curr = curr.next
        length += 1
    }


    var mid_point = parseInt(length / 2) + 1


    // reset current to head (reuse the variable)
    curr = head
    // reset length to 0 (reuse the variable)
    length = 0;
    var found = false; // termination flag for when the index is found in the loop

    // Another loop to fetch the linked list node
    while (!found || curr !== null) {
        if (length == mid_point - 1) {
            found = curr;
            break;
        }


        curr = curr.next
        length += 1
    }


    return found
};