Skip to content

Commit 2437148

Browse files
authored
141. Linked List Cycle
141. Linked List Cycle
1 parent 147e51e commit 2437148

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

hasCycle.cpp

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// uses slow and fast pointer
2+
// if there is a cycle, the slow and fast pointer will meet at some point of time and we return true
3+
// else, the while loop will break at the end of the dead end of the list and we return false
4+
class Solution {
5+
public:
6+
bool hasCycle(ListNode *head) {
7+
if(!head) return false;
8+
ListNode* slow = head;
9+
ListNode* fast = head;
10+
while(fast->next && fast->next->next){
11+
slow = slow->next;
12+
fast = fast->next->next;
13+
if(slow == fast) return true;
14+
}
15+
return false;
16+
}
17+
};

0 commit comments

Comments
 (0)