快慢指针
/**
* 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) {
//快慢指针的方法
ListNode* fast = head;
ListNode* slow = head;
while(fast != NULL && slow != NULL)
{
slow = slow->next;
if(fast->next != NULL)
{
fast = fast->next->next;
}else{
return false;
}
if(fast == slow)
{
return true;
}
}
return false;
}
};
哈希表的方式
/**
* 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*> visited;
ListNode* cur = head;
while(cur != NULL)
{
if(visited.find(cur) == visited.end())
{
visited.insert(cur);
}else{
return true;
}
cur = cur->next;
}
return false;
}
};