141. 环形链表———附带详细代码和思路
发布时间:2023-02-03 13:46:03 187
相关标签:
1 题目
2 思路
2.1 思路一
使用哈希表存储每次遍历后的指针的地址,遍历链表,如果遍历结束前,发现哈希表中已存在目前遍历的指针地址,就返回false,否则返回true。
2.2 思路二
摘自官网解说
3 代码
3.1 代码1
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set 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;
}
};
文章来源: https://blog.51cto.com/u_10941874/5780972
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报