-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLinkedListCycleLength.java
More file actions
45 lines (38 loc) · 943 Bytes
/
LinkedListCycleLength.java
File metadata and controls
45 lines (38 loc) · 943 Bytes
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
/*
Pattern: Fast & Slow pointers
01.5 LinkedList Cycle Length (easy)
Given the head of a LinkedList with a cycle, find the length of the cycle.
*/
class ListNode {
int value = 0;
ListNode next;
ListNode(int value){
this.value = value;
}
}
class LinkedListCycleLength{
public static int findCycleLength(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return getCycleLength(slow);
}
}
return 0; // no cycle
}
private static int getCycleLength(ListNode slow){
ListNode current = slow;
int cycleLength = 0;
do {
current = current.next;
cycleLength++;
} while(current != slow);
return cycleLength;
}/*
Time Complexity: O(N)
Space Complexity: O(1)
*/
}