1.方法1,hash表
我们遍历链表中的每个节点,并将它记录下来;一旦遇到了此前遍历过的节点,就可以判定链表中存在环。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode *> visited;
while (head != nullptr) {
if (visited.count(head)) {
return head;
}
visited.insert(head);
head = head->next;
}
return nullptr;
}
};
2.快慢指针
当快慢指针第一次相遇时,新建pw = head;pw与slow每次走一步, 最终这时 slow和pw在入口相遇
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode * slow = head , * fast = head;
while(fast){
slow = slow->next;
if(fast->next == nullptr)
return nullptr;
fast = fast->next->next;
if(fast == slow){
ListNode *pw = head;
while(pw != slow){
pw = pw->next;
slow = slow->next;
}
return pw;
}
}
return nullptr;
}
};