题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
快慢指针法判断是否有环,若有环,则快慢指针相遇结点与头结点依次后移一位会相遇在入口结点
时间复杂度O(n),空间复杂度:O(1)
struct ListNode* EntryNodeOfLoop(struct ListNode* pHead ) {
// write code here
struct ListNode* head = pHead;
struct ListNode* fast = pHead;
struct ListNode* slow = pHead;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
while (fast != head) {
fast = fast->next;
head = head->next;
}
return fast;
}
}
return NULL;
}