问题:环形链表
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200306202857493.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1NvbmdCYWkxOTk3,size_16,color_FFFFFF,t_70
解题思路
使用集合set存放已经出现的节点,如果在遍历结束之前访问了set中已经有的节点,说明有环,否则没有环。
C++代码
/**
* 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*> s;
while(head){
if(s.find(head) != s.end()) return true;
s.insert(head);
head = head->next;
}
return false;
}
};
问题:环形链表 II
解题思路
使用集合set存放已经出现的节点,如果在遍历结束之前访问了set中已经有的节点,说明有环,且第一个是入环的节点,否则没有环。
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*>s;
while(head){
if(s.find(head) != s.end())//如果此节点已经被访问
return head;
else
s.insert(head);//将访问过的节点插入集合中
head = head->next;
}
return NULL;//没有环,返回NULL
}
};