-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathDetectCycleInLL.java
More file actions
58 lines (55 loc) · 1.34 KB
/
DetectCycleInLL.java
File metadata and controls
58 lines (55 loc) · 1.34 KB
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
57
58
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
https://leetcode.com/problems/linked-list-cycle/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
if(head.next==null){
return false;
}
ListNode slow ;
ListNode fast;
// slow = head;
//fast = head.next;
slow = fast = head;
while(slow!=null && fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
/*if(fast == null || fast.next==null){
return false;
}*/
}
return false;
}
/*
public boolean hasCycle(ListNode head) {
HashMap<ListNode, Boolean> visitedMap = new HashMap<>();
ListNode temp = head;
while(temp!=null){
ListNode ref = temp;
if(visitedMap.get(ref)!=null){
return true;
}
else{
visitedMap.put(ref, true); // Visited Mark
}
temp = temp.next;
}
return false;
}
*/
}