-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycleII.java
More file actions
50 lines (43 loc) · 1.28 KB
/
LinkedListCycleII.java
File metadata and controls
50 lines (43 loc) · 1.28 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
package linkedlist;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 12/02/2019
*
* 142. Linked List Cycle II
* https://leetcode.com/problems/linked-list-cycle-ii/
* Difficulty: Medium
*
* Approach: Floyd's Cycle Detection
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle II.
* Memory Usage: 34.5 MB, less than 95.79% of Java online submissions for Linked List Cycle II.
*
* Time Complexity: O(n)
* Space Complexity: O(1)
* Where n is the number of nodes in the linked list
*
* @see LinkedListTest#testLinkedListCycleII()
*/
public class LinkedListCycleII {
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null){
return null;
}
ListNode slow = head.next;
ListNode fast = head.next.next;
while(slow != null && fast != null && fast.next != null && slow != fast){
slow = slow.next;
fast = fast.next.next;
}
if(fast == null || fast.next == null){
return null;
}else{
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return fast;
}
}
}