题目:
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?
思路:
当快慢指针相遇时,让慢指针指向头节点,快指针变成每次移动一步,当两个指针相遇的时候,那个节点就是环的起点。
代码:
public ListNode detectCycle(ListNode head) {
if(head == null || head.next == null)
return null;
ListNode slow = head;
ListNode fast = head;
ListNode begin = null;
while(fast != null && fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
begin = slow;
break;
}
}
return begin;
}