diff --git a/src/LinkedListCycle141.java b/src/LinkedListCycle141.java index 01a913a..16f4e72 100644 --- a/src/LinkedListCycle141.java +++ b/src/LinkedListCycle141.java @@ -21,18 +21,29 @@ public class LinkedListCycle141 { public boolean hasCycle(ListNode head) { - ListNode slow = head; - ListNode fast = head; + // ListNode slow = head; + // ListNode fast = head; - while(slow != null && fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; + // while(slow != null && fast != null && fast.next != null) { + // slow = slow.next; + // fast = fast.next.next; - if (slow == fast) { + // if (slow == fast) { + // return true; + // } + // } + + // return false; + // Approach 2: + HashSet visited = new HashSet<>(); + ListNode current = head; + while (current != null) { + if (visited.contains(current)) { return true; } + visited.add(current); + current = current.next; } - return false; } }