对于一个给定的链表,返回环的入口节点,如果没有环,返回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) {
//快慢指针找中点
ListNode slow =head;
ListNode fast=head;
while(fast!=null&&fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
//找环入口
if (slow == fast) { //快慢指针相遇
ListNode slow2 = head;
while (slow != slow2) {
slow = slow.next;
slow2 = slow2.next;
}
return slow; //环入口
}
}
return null;//没有环
}
}