Skip to content

Commit 26f04d4

Browse files
authored
detect loop in LL
1 parent ceda164 commit 26f04d4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

flyodDetectLoop.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
bool hasCycle(ListNode *head) {
12+
if(head == NULL){
13+
return false;
14+
}
15+
16+
ListNode* fast = head;
17+
ListNode* slow = head;
18+
19+
while(fast != NULL && fast->next != NULL){
20+
fast = fast->next;
21+
22+
if(fast != NULL){
23+
fast = fast->next;
24+
}
25+
26+
slow = slow->next;
27+
28+
if(slow == fast){
29+
return true;
30+
}
31+
}
32+
return false;
33+
}
34+
};

0 commit comments

Comments
 (0)