[leetcode #142] Linked List Cycle II

Seongyeol Shin·2022년 1월 20일
0

leetcode

목록 보기
135/196
post-thumbnail

Problem

Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Constraints:

・ The number of the nodes in the list is in the range [0, 10⁴].
・ -10⁵ <= Node.val <= 10⁵
・ pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Idea

주어진 list에 cycle이 있는지 확인하고, cycle이 있다면 가장 끝의 노드가 가리키는 노드가 어떤 것인지 구하는 문제다.

가장 간단하게 푸는 건 set을 이용하는 것이다. list를 탐색하면서 노드를 set에 더하고, set에 해당 노드가 있을 때 cycle이 존재한므로 해당 노드를 리턴하면 된다.

하지만 space complexity를 O(1)로 해서 푸는 방법도 존재한다.

리스트를 탐색할 때 노드를 하나씩 움직이는 포인터와 두 개씩 움직이는 포인터를 만들고 두 포인터가 만나는지 확인한다. Cycle이 존재한다면 두 포인터는 반드시 만나게 되어 있다. Cycle이 존재할 경우 하나씩 움직이는 포인터를 head로 설정하고 두 포인터를 하나씩 옮겨서 만나는 지점을 확인한다. 이 때 만나는 노드가 tail이 가리키는 노드이므로 해당 노드를 리턴하면 된다.

Solution

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

        ListNode next = head.next;
        ListNode doubleNext = head.next.next;
        boolean isCycle = false;

        while (doubleNext != null && doubleNext.next != null) {
            if (next == doubleNext) {
                isCycle = true;
                break;
            }

            next = next.next;
            doubleNext = doubleNext.next.next;
        }

        if (!isCycle) {
            return null;
        }

        next = head;
        while (next != doubleNext) {
            next = next.next;
            doubleNext = doubleNext.next;
        }

        return next;
    }
}

Reference

https://leetcode.com/problems/linked-list-cycle-ii/

profile
서버개발자 토모입니다

0개의 댓글