给定一个链表,返回链表开始入环的第一个节点。?如果链表无环,则返回?null 。
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null) {
fast = fast.next;
if (fast == null) {
return null;
} else {
fast = fast.next;
}
slow = slow.next;//快指针走两步,慢指针走一步
if (fast == slow) {
ListNode t = head;
//快慢指针相遇后,设一个新指针,从头开始,和慢指针一起走,相遇处就是入口
while (t != slow) {
t = t.next;
slow = slow.next;
}
return t;
}
}
return null;
}
}
|