Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
這道題是快慢指針的經典應用。
step1:
設兩個指針,一個每次走一步的慢指針和一個每次走兩步的快指針,如果鏈表裏有環的話,兩個指針最終肯定會相遇。
step2:
記錄兩個指針相遇的位置,當兩個指針相遇了後,讓其中一指針從鏈表頭開始,此時再相遇的位置就是鏈表中環的起始位置。
public class l142_linked_list_cycle {
class ListNode{
int val;
ListNode next;
ListNode(int x){
val=x;
next=null;
}
}
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==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) return null;
slow=head;
while (slow!=fast){
slow=slow.next;
fast=fast.next;
}
return slow;
}
}