Skip to content

Commit fb52881

Browse files
committedMay 2, 2022
updates linked list cycle
1 parent c451a76 commit fb52881

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed
 

‎src/LinkedListCycle.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
import java.util.HashSet;
2-
import java.util.Set;
1+
// T: O(n)
2+
// S: O(1)
33

44
public class LinkedListCycle {
5-
static class ListNode {
5+
private static class ListNode {
66
int val;
77
ListNode next;
88
ListNode(int x) {
9-
val = x;
10-
next = null;
9+
val = x;
10+
next = null;
1111
}
1212
}
1313

1414
public boolean hasCycle(ListNode head) {
15-
Set<ListNode> nodes = new HashSet<>();
16-
while (head != null) {
17-
if (nodes.contains(head)) {
18-
return true;
19-
} else {
20-
nodes.add(head);
21-
}
22-
head = head.next;
15+
if (head == null) return false;
16+
17+
for (ListNode slow = head, fast = head.next; fast != null && fast.next != null ; ) {
18+
if (slow == fast) return true;
19+
slow = slow.next;
20+
fast = fast.next.next;
2321
}
22+
2423
return false;
2524
}
2625
}

0 commit comments

Comments
 (0)
Please sign in to comment.