Linked List Cycle II

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

Note: Do not modify the linked list.

Solution

Solution using hash set.

/**
 * 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) {
        // 2
        Set<ListNode> set = new HashSet<>();

        ListNode current = head;
        while (current != null) {
            if (set.contains(current)) {
                return current;
            } else {
                set.add(current);
            }

            current = current.next;
        }

        return null;
    }
}

Other solution using two pointers.

Last updated

Was this helpful?