Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up: Can you solve it without using extra space?
s思路: 1. 如何用快慢指針大法檢測cycle,在Leetcode 141. Linked List Cycle以及說清楚了。不說了,直接來!
//方法1:快慢指針移動大法!class Solution {public: ListNode *detectCycle(ListNode *head) { // if(!head) return NULL; ListNode* fast=head->next,*slow=head; while(fast&&fast!=slow){ fast=fast->next?fast->next->next:NULL; slow=slow->next; } if(fast==NULL) return NULL; fast=head; slow=slow->next;//這里有一個bug:把fast放在頭部,那么slow需要往下移動一位,才開始同步移動! while(fast!=slow){ fast=fast->next; slow=slow->next; } return fast; }};新聞熱點
疑難解答