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?
在一个单链表中找到又换的单链表的入口的节点,在这道题中,首先先的判断该单链表是不是有环,设置slow和fast来判断是不是有环,在找到第一次相遇的节点时记下该节点,然后让slow从头开始,fast为相遇的节点,下面就从slow开始,当slow==fast时就找到了入口点,以为fast总是快于slow两步,当从头开始时一定会相遇并且为入口点(当该链表有环时)
public ListNode detectCycle(ListNode head) {
if(head==null||head.next==null) return null;
ListNode fast=head;
ListNode slow=head;
//找到第一次相遇的节点也就是判断单链表是否有环
//fast以一次两步的节奏向前推进,而fast一次一个节奏向前推进
//如果有环的话总会相遇的
while(fast!=null&&slow!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
//找到第一次相遇地方退出循环
if(slow==fast) break;
}
//当fast==null说明没有环
if(fast==null||fast.next==null)return null;
//把slow职位head当从头开始遍历链表时slow和fast以相同的步调向前推进
//当slow==fast时就找到了入口点
slow=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return fast;
}