[LeetCode] Linked List Cycle II

来源:互联网 发布:pos机s90如何设置网络 编辑:程序博客网 时间:2024/06/05 05:31
ListNode *detectCycle(ListNode *head) {ListNode* pFast = head;ListNode* pSlow = head;do{if(pFast == NULL){return NULL;}else if(pFast->next == NULL){return NULL;}pFast = pFast->next->next;pSlow = pSlow->next;}while(pFast != pSlow);ListNode* pSlow2 = head;while(pSlow != pSlow2){pSlow = pSlow->next;pSlow2 = pSlow2->next;}return pSlow;}
用Linked List Cycle快慢指针的方法找着循环上的一个节点,将快指针移回链表头,并以与慢指针相同的速度移动,直至两指针重合,即为循环起始位置。
0 0
原创粉丝点击