forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListCycle.java
56 lines (48 loc) · 1.08 KB
/
LinkedListCycle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
//TC: O(n)
//SC: O(n)
Set<ListNode> set = null;
public boolean hasCycle(ListNode head) {
set = new HashSet<>();
ListNode it = head;
while(it!=null){
if(set.contains(it)){
return true; // cycle found
}
set.add(it);
it = it.next;
}
return false;
}
// TC : O(n)
// SC : O(1)
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast!= null && fast.next!=null){
slow = slow.next;
fast = fast.next;
if(fast!=null){
fast = fast.next;
}
if(slow == fast){
return true;
}
}
return false;
}
}