标签:lazy leetcode mamicode amp tco ret lse image ==
题目:
/**
* 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;
}
};
LeetCode——142. Linked List Cycle II
标签:lazy leetcode mamicode amp tco ret lse image ==
原文地址:https://www.cnblogs.com/yejianying/p/LeetCode_142_Linked_List_Cycle_II.html