LeetCode——142. Linked List Cycle II
题目:
/**
* 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) {
auto slow = head, fast = head;
auto hasLoop = false;
if (slow == nullptr) {
return nullptr;
}
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
hasLoop = true;
break;
}
}
if (hasLoop == false) {
return nullptr;
}
slow = head;
while(fast != slow) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
本博客文章默认使用CC BY-SA 3.0协议。