标签:lse ace fast null class false 处理 head end
利用set容器处理
public:
bool hasCycle(ListNode *head) {
set<ListNode*> save;
while(head != nullptr){
if(save.find(head)!=save.end())
return true;
save.emplace(head);
head=head->next;
}
return false;
}
快指针每次走两步,慢指针每次走一步,设两指针相遇点为meet,那么从meet和head同时出发,同样速度前进,相遇节点即为环的起点
bool hasCycle(ListNode *head) {
if (head == nullptr)
return false;
ListNode *slow = head, *fast = head;
while (true) {
if (fast->next == nullptr || fast->next->next == nullptr)
return false;
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
}
标签:lse ace fast null class false 处理 head end
原文地址:https://www.cnblogs.com/INnoVationv2/p/10152509.html