[LeetCode] Middle of the Linked List

아르당·2026년 3월 6일

LeetCode

목록 보기
188/211
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

단일 연결 리스트 head가 주어졌을 때, 연결 리스트의 중간 노드를 반환해라.
중간 노드가 두 개 있는 경우, 두 번째 노드를 반환해라.

Example

#1

Input: head = [1, 2, 3, 4, 5]
Output: [3, 4, 5]
Explanation: 리스트의 중간 노드는 3이다.

#2

Input: head = [1, 2, 3, 4, 5, 6]
Output: [4, 5, 6]
Explanation: 리스트에는 값이 3과 4인 중간 노드가 두 개 있으므로 두 번째 노드를 반환한다.

Constraints

  • 리스트의 노드 수는 [1, 100] 범위에 있다.
  • 1 <= Node.val <= 100

Solved

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        ListNode slow = head;
        ListNode fast = head;

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

        return slow;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글