142. 环形链表 II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以使用 O(1) 空间解决此题?
/**
* 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) {
ListNode slow=head;
ListNode fast=head;
boolean exist=false;
if (head==null){
return head;
}
while(slow.next!=null&&fast.next!=null&&fast.next.next!=null){
//防止数组越界
slow=slow.next;
fast=fast.next.next;
if (slow==fast){
exist=true;
break;
}
}
//有环
if(exist==true){
fast=head;
while(fast!=slow) {
fast=fast.next;
slow=slow.next;
}
return fast;
}
return null;
}
}
补充:
Floyd判圈法