Topic links: Click here
set heavy sentence:
/**
* 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) {
unordered_set<ListNode*> st;
while(head!=NULL)
{
if(st.count(head)) return true;
st.insert(head);
head = head->next;
}
return false;
}
};
map:
/**
* 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) {
unordered_map<ListNode*, int> mp;
while(head!=NULL)
{
if(mp[head]==2) return true;
mp[head]++;
head = head->next;
}
return false;
}
};
Pointer speed:
Characterized by a single list of each node knows only the next node, so that only determines whether or not a pointer list containing ring.
-
If the list does not contain the ring, then the pointer will eventually encounter a null pointer or null list coming to an end, this is better said, can determine this list does not contain ring.
-
But if the list contains a loop, then the pointer will be caught in an infinite loop, because the annular array is not null pointer as the tail node.
Classic solution is to use two hands, a run fast, a slow runner.
- If the ring is not contained, the pointer to run faster eventually encounter null, list description no ring;
- If the ring containing, ultra-fast pointer will eventually slow the pointer around, and slow to meet this pointer indicates the list containing ring.
/**
* 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, *slow = head;
while(fast!=NULL && fast->next!=NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast==slow) return true;
}
return false;
}
};