[JS] Middle of the Linked List

2022. 7. 29. 16:21

🔒 문제 (LeetCode 876)

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.

Constraints:

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

 

🌊 입출력

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.

 


 

🔑 해결

🌌 알고리즘 - two pointers

중간 노드는 끝 노드 인덱스의 절반 지점에 위치.

slow로 중간 노드를 찾고 fast는 마지막 노드를 찾는다. slow는 한 칸씩, fast는 두 칸씩 이동하다가 fast가 마지막 노드에 도달하면 slow가 절반 지점의 노드를 찾는다.

/**
 * 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 && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    
    return slow;
};

+ Recent posts