Linked List Cycle 代码
/**
* 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 *p1;
p1 = head;
while(p1 != NULL) {
if(visited.count(p1))
return true;
else
visited.insert(p1);
p1 = p1->next;
}
return false;
}
};
Linked List Cycle II 代码
/**
* 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 *> visited;
ListNode *p1;
p1 = head;
while(p1 != NULL) {
if(visited.count(p1))
return p1;
else
visited.insert(p1);
p1 = p1->next;
}
return NULL;
}
};