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?
/**
* 解题思路:
* 1.定义快慢指针(虽然Java里面没有指针的概念,但还是感觉这个词比较形象)指向head节点;
* 2.当fast指针非空,且它的next节点非空时,slow指针每次走1步,fast指针每次走2步,如果二者相遇了(说明存在环)就退出当前循环;
* 3.fast指针指向head节点,slow仍在相遇节点,二者同时开始每次走一步,再次相遇时即为环开始的位置。
*
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if( head==null)
return null;
ListNode slow = head;
ListNode fast = head;
while( fast!=null && fast.next!=null ){
slow = slow.next;
fast = fast.next.next;
if( slow==fast ){
break;
}
}
if( fast!=null && fast.next!=null ){
fast = head;
while( fast!=slow ){
fast = fast.next;
slow = slow.next;
}
return fast;
}
return null;
}
}