File tree
Expand file treeCollapse file tree1 file changed
+18
-7
lines changed Expand file treeCollapse file tree1 file changed
+18
-7
lines changed Original file line number | Diff line number | Diff line change |
---|
|
21 | 21 |
|
22 | 22 | public class LinkedListCycle141 {
|
23 | 23 | public boolean hasCycle(ListNode head) {
|
24 |
| -ListNode slow = head; |
25 |
| -ListNode fast = head; |
| 24 | +// ListNode slow = head; |
| 25 | +// ListNode fast = head; |
26 | 26 |
|
27 |
| -while(slow != null && fast != null && fast.next != null) { |
28 |
| -slow = slow.next; |
29 |
| -fast = fast.next.next; |
| 27 | +// while(slow != null && fast != null && fast.next != null) { |
| 28 | +// slow = slow.next; |
| 29 | +// fast = fast.next.next; |
30 | 30 |
|
31 |
| -if (slow == fast) { |
| 31 | +// if (slow == fast) { |
| 32 | +// return true; |
| 33 | +// } |
| 34 | +// } |
| 35 | + |
| 36 | +// return false; |
| 37 | +// Approach 2: |
| 38 | +HashSet<ListNode> visited = new HashSet<>(); |
| 39 | +ListNode current = head; |
| 40 | +while (current != null) { |
| 41 | +if (visited.contains(current)) { |
32 | 42 | return true;
|
33 | 43 | }
|
| 44 | +visited.add(current); |
| 45 | +current = current.next; |
34 | 46 | }
|
35 |
| - |
36 | 47 | return false;
|
37 | 48 | }
|
38 | 49 | }
|
You can’t perform that action at this time.
0 commit comments