-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm142.java
More file actions
59 lines (54 loc) · 1.5 KB
/
prblm142.java
File metadata and controls
59 lines (54 loc) · 1.5 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
59
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class prblm142 {
public static void main(String[] args) {
//Self Made LinkedList to check the code
ListNode l1 = new ListNode(3);
ListNode l2 = new ListNode(2);
ListNode l3 = new ListNode(0);
ListNode l4 = new ListNode(-4);
ListNode head = l1;
l1.next = l2;
l2.next = l3;
l3.next = l4;
l4.next = l2;
System.out.println(detectCycle(head).val);
}
public static ListNode detectCycle(ListNode head) {
//unoptimized code(using hashmap)
// Map<ListNode,Boolean> map = new HashMap<>();
// ListNode curr = head;
// while(curr != null){
// if (map.containsKey(curr)) {
// return curr;
// }
// else{
// map.put(curr, true);
// curr = curr.next;
// }
// }
// return null;
//optimized solution(using fast and slow pointers)
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}