1.题目
2.解法(快慢指针)
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
// 如果没有点或者1个点,那么返回null
if(pHead == null || pHead.next == null){
return null;
}
//定义快慢指针
ListNode fast = pHead;
ListNode slow = pHead;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
//如果有环,想遇于环中某点
if (fast == slow) {
break;
}
}
//如果没有环,return null
if (slow == null) {
return null;
}
//如果有环,两个指针分别从链表头和相遇点出发,最终必定在环入口相遇
slow = pHead;
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
时间复杂度:O(n)
空间复杂度:O(1)