方法一:
实现思路
遍历链表,同时将遍历的元素添加到集合中,判断集合中是否出现过该元素,如果出现过,则说明链表中有环存在。
实现代码
141代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
set<ListNode*> snode;
while(head!=nullptr){
snode.insert(head);
head=head->next;
if(snode.find(head)!=snode.end())
return true;
}
return false;
}
};
142代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> snode;
while(head!=nullptr){
snode.insert(head);
head=head->next;
if(snode.find(head)!=snode.end())
return head;
}
return nullptr;
}
};
提交结果及分析:
时间复杂度O(n(logn)),空间复杂度O(n)
方法二
实现思路
有环的时候才会出现快指针扣圈的情况
这一推导,有助于下面求解相交节点