File tree Expand file tree Collapse file tree 1 file changed +12
-13
lines changed Expand file tree Collapse file tree 1 file changed +12
-13
lines changed Original file line number Diff line number Diff line change 1
- import java . util . HashSet ;
2
- import java . util . Set ;
1
+ // T: O(n)
2
+ // S: O(1)
3
3
4
4
public class LinkedListCycle {
5
- static class ListNode {
5
+ private static class ListNode {
6
6
int val ;
7
7
ListNode next ;
8
8
ListNode (int x ) {
9
- val = x ;
10
- next = null ;
9
+ val = x ;
10
+ next = null ;
11
11
}
12
12
}
13
13
14
14
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 ;
23
21
}
22
+
24
23
return false ;
25
24
}
26
25
}
You can’t perform that action at this time.
0 commit comments