/*
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
*/
//Runner Technique Again
//Two points: slow and fast,
//1.slow: move one step at time
//2.fast: move two steps at time
//3.while two points(slow and fast) are encounter => hasCycle => break
//4.Set slow point back to head to find node point of cycle begin.
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null)
return null;
if (head.next == null)
return null;
//handle the base case of {1} tail connects to head itself
if(head.next ==head) return head;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
//handle the case of noCycle that make sure there is cycle exist
if(slow==null || fast ==null || fast.next==null){
return null;
}
//move slow point to the head
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
//when two point slow and fast encounter again,
//return either slow or fast for point of cycle begin
return slow;
}
}
Linked List Cycle II Java
最新推荐文章于 2020-12-14 02:16:15 发布