[LeetCode] Middle of the Linked List

준규·2022년 12월 27일

1.문제


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.


단일 연결리스트가 주어질 때 연결리스트의 중간 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.

Constraints:

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

2.풀이

  1. 연결리스트의 중간 인덱스를 구한다.
  2. 연결리스트를 순회하면서 중간 node를 head로 바꾸어준다.

/**
 * 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}
 */
const middleNode = function (head) {
  // 리스트의 길이 구하는 함수
  const getLength = (head) => {
    let current = head;
    let length = 0;
    while (current !== null) {
      if (current) {
        length++;
        current = current.next;
      }
    }
    return length;
  };

  // 리스트의 중간 인덱스 구하기
  const middle = Math.floor(getLength(head) / 2);

  let current = head;
  let count = 0;
  // 리스트를 순회하면서 중간인덱스부분을 head로 변경해준다.
  while (current !== null) {
    if (count === middle) {
      head = current;
      break;
    }
    count++;
    current = current.next;
  }

  return head;
};

3.결과

profile
안녕하세요 :)

0개의 댓글