-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLinkedListCycleStart.java
More file actions
63 lines (56 loc) · 1.6 KB
/
LinkedListCycleStart.java
File metadata and controls
63 lines (56 loc) · 1.6 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
60
61
62
63
/*
Pattern: Fast & Slow pointers
02 Start of LinkedList Cycle (medium)
Given the head of a Singly LinkedList that contains a cycle,
write a function to find the starting node of the cycle.
# 142. Linked List Cycle II (Medium)
[Result]
Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle II.
Memory Usage: 35.5 MB, less than 5.04% of Java online submissions for Linked List Cycle II.
*/
class ListNode {
int value = 0;
ListNode next;
ListNode(int value){
this.value = value;
}
}
class LinkedListCycleStart {
public static ListNode detectCycle(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
int cycleLength = getCycleLength(slow);
return findStartingNodeCycle(head, cycleLength);
}
}
return null; // no cycle
}
private static int getCycleLength(ListNode slow){
ListNode current = slow;
int cycleLength = 0;
do {
current = current.next;
cycleLength++;
} while(current != slow);
return cycleLength;
}
private static ListNode findStartingNodeCycle(ListNode head, int cycleLength){
ListNode pointer1 = head;
ListNode pointer2 = head;
for(int i=0; i<cycleLength; i++){
pointer2 = pointer2.next;
}
while(pointer1 != pointer2){
pointer1 = pointer1.next;
pointer2 = pointer2.next;
}
return pointer1;
}
}/*
Time Complexity: O(N)
Space Complexity: O(1)
*/