给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
/**
* 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,遍历head插入到set中,再次遍历时候查找,查找到则是起点
set<ListNode*>node_set;
while(head)
{
if(node_set.find(head) != node_set.end())
{
return true;
}
node_set.insert(head);
head = head->next;
}
return false;
}
};