[leetcode #876] Middle of the Linked List

Seongyeol Shin·2021년 12월 28일
0

leetcode

목록 보기
118/196
post-thumbnail

Problem

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.

Constraints:

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

Idea

리스트의 중간 지점을 찾는 문제다.
탐색하면서 Array에 ListNode를 저장한 뒤, Array의 가운데 지점을 리턴하는 방식도 있지만, 이 방법은 space complexity가 O(N)이다.
더 좋은 방법은 fast pointer를 이용하는 것이다. slow pointer가 노드 하나씩 이동한다면, fast pointer는 두 개씩 이동한다. fast pointer가 리스트의 끝 부분에 도착했을 경우, slow pointer는 리스트의 중간 지점을 가리키게 되므로 slow pointer를 리턴하면 된다.

Solution

/**
 * 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) {
        ListNode node = head;
        ListNode doubleJump = head;

        while (doubleJump != null && doubleJump.next != null) {
            node = node.next;
            doubleJump = doubleJump.next.next;
        }

        return node;
    }
}

Reference

https://leetcode.com/problems/middle-of-the-linked-list/

profile
서버개발자 토모입니다

0개의 댓글