Discription:
Given a linked list, determine if it has a cycle in it.
Solution:
bool hasCycle(ListNode *head) {
if (!head) return false;
ListNode *pslow = head, *pfast = head;
while (pfast && pfast->next)
{
pfast = pfast->next->next;
pslow = pslow->next;
if (pfast == pslow){
return true;
}
}
return false;
}
Discription:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Solution:
ListNode *detectCycle(ListNode *head) {
if (!head) return NULL;
ListNode *pslow = head, *pfast = head;
while (pfast && pfast->next)
{
pfast = pfast->next->next;
pslow = pslow->next;
if (pfast == pslow){
pslow = head;
while (pfast != pslow){
pfast = pfast->next;
pslow = pslow->next;
}
return pfast;
}
}
return NULL;
}
GitHub-LeetCode:
https://github.com/wenwu313/LeetCode