Leetcode Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
借用博客http://www.cnblogs.com/hiddenfox/p/3408931.html的图
设环的距离为L = (b+c),无环的距离为a,
假设在时间t相遇,慢指针行驶距离为x,则 1 x t = x,即t=x
则快指针行驶的距离为2t = 2x,
则慢指针环上停留点为(x-a)%L,快指针停留点为 (2x-a)%L,由于在t时刻相遇,故(x-a)%L = (2x-a)%L,
根据同余定理 x%L = 0,
当快指针相遇后减慢速度为1,快指针从z继续行走a长度停下,则行走的路程为2x+a,在环上的位置为(2x+a-a)%L = 2x%L=2(x%L) = 0,即回到环的起始点,故知道环的起始点
ListNode* hasCycle(ListNode* head){ if(head == NULL || head->next == NULL) return false; ListNode* first = head, *second = head; while(second!=NULL && second->next!=NULL){ first = first->next; second = second->next->next; if(first == second) return first; } return NULL; } ListNode *detectCycle(ListNode *head){ ListNode* cycleNode = hasCycle(head); if(cycleNode != NULL){ ListNode* startNode = head; while(startNode!=cycleNode){ cycleNode = cycleNode->next; startNode = startNode->next; } } return cycleNode; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步