LeetCode - 876. Middle of the Linked List | Lacerta

876. Middle of the Linked List

BF

实现

遍历数组,记下长度,再遍历一次,返回一半的那个节点

提示I - Double Pointer

实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var middleNode = function(head) {
    let slow = head;
    let fast = head;

    while (fast !== null && fast.next !== null) {
        slow = slow.next;
        fast = fast.next.next;
    }

    return slow;
};