[leetCode] 876. Middle of the Linked List

3335 ワード

🧪 Description


Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.

Example 1:


Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:


Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

💊 Solution


この問題は接続リストを使用する問題です.
データ構造接続リストとは?
接続リストにアクセスする方法を知る必要があります.
/**
 * 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) {
    let slow = head;
    let fast = head;
    while(fast !== null) {
        fast = fast.next;
        if (fast === null) break;
        else {
            fast = fast.next;
        }
        slow = slow.next;
    }
    return slow;
};

🧫 Result


Runtime


76 ms, faster than 57.09% of JavaScript online submissions for Middle of the Linked List.

Memory Usage


39.2 MB, less than 7.70% of JavaScript online submissions for Middle of the Linked List.