Linked List Cycle II
Total Accepted: 77103
Total Submissions: 246124
Difficulty: Medium
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.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
Hide Similar Problems
c++ code:
/**
* 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) {
if(NULL == head) return NULL;
ListNode *slow, *fast;
fast = slow = head;
int isCircle = false;
while(slow && fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(fast == slow)
{
isCircle = true;
break;
}
}
if(!isCircle) return NULL;
fast=head;
while(fast != slow) {
slow = slow->next;
fast = fast->next;
}
return slow;
}
};