https://leetcode.com/problems/linked-list-cycle-ii/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins.
* if there is no cycle, return null
*/
ListNode *detectCycle(ListNode *head) {
if (!head) return head;
ListNode *slow = head, *fast = head;
bool isCycle = false;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow) {
isCycle = true;
break;
}
}
if (!isCycle) return NULL;
ListNode *u = head;
while (u != slow) {
u = u->next;
slow = slow->next;
}
return u;
}
};
参考:http://ihuafan.com/%E7%AE%97%E6%B3%95/floyds-cycle-finding-algorithm
转载于:https://www.cnblogs.com/ilovezyg/p/6388432.html
687




被折叠的 条评论
为什么被折叠?



