文章目录
1 题目
2 思路
2.1 思路一
使用哈希表存储每次遍历后的指针的地址,遍历链表,如果遍历结束前,发现哈希表中已存在目前遍历的指针地址,就返回false,否则返回true。
2.2 思路二
摘自官网解说
3 代码
3.1 代码1
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while(head != nullptr){
if(seen.count(head) > 0){
return true;
}else{
seen.insert(head);
}
head = head->next;
}
return false;
}
};
3.2 代码2
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr){
return false;
}
ListNode *slow = head, *fast = head->next;
while(slow != fast){
if(fast == nullptr || fast->next == nullptr){
return false;
}
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};