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?
解题思路,本题和上题十分类似,但是需要观察出一个规律,参考LeetCode:Linked List Cycle II
JAVA实现如下:
public ListNode detectCycle(ListNode head) {
ListNode fast = head, slow = head;
boolean isLoop=false;
while (fast != null) {
slow = slow.next;
ListNode temp = fast.next;
if (temp == null)
return null;
fast = temp.next;
if (fast == slow){
isLoop=true;
break;
}
}
while (isLoop) {
if (slow == head)
return slow;
slow = slow.next;
head = head.next;
}
return null;
}