Skip to content

Commit a61ceda

Browse files
committed
Time: 6 ms (90.60%), Space: 7.4 MB (98.05%) - LeetHub
1 parent 6bcd2cb commit a61ceda

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *detectCycle(ListNode *head) {
12+
if(head == NULL || head -> next == NULL)
13+
return NULL;
14+
ListNode *slow = head,*fast = head, *temp = head;
15+
16+
while(fast != NULL && fast -> next != NULL)
17+
{
18+
slow = slow -> next;
19+
fast = fast -> next -> next;
20+
21+
if(fast == slow) //cycle || loop
22+
{
23+
while(slow != temp)
24+
{
25+
slow = slow -> next;
26+
temp = temp -> next;
27+
}
28+
return temp ;
29+
}
30+
31+
}
32+
33+
34+
return NULL;
35+
}
36+
};

0 commit comments

Comments
 (0)