LeetCode 142. Linked List Cycle II
Solution1:我的答案
这道题多次遇到,牢记此解法
这道题要深思一下,快指针和慢指针的速度对比不同,会产生什么不同的结果?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == NULL)
return NULL;
struct ListNode *slow = head, *fast = head;
bool cycle = false;
while (slow->next && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
cycle = true;
break;
}
}
if (!cycle)
return NULL;
struct ListNode* cur = head;
while (cur != slow) {
cur = cur->next;
slow = slow->next;
}
return cur;
}
};