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?
给定一个链表,判断是否有环,如果没有环,直接返回null。(解决这个问题而不需要额外的空间)
/**
* 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 head;
ListNode slow = head;
ListNode fast = head;
boolean isCircle = false;
//快慢指针判断是否有环
while(fast != null && fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
isCircle = true;
break;
}
}
//环不存在
if(!isCircle){
return null;
}
//其中一个指针从头开始遍历,下一次两个指针相遇的结点就是环的入口
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}