8000
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 6b88dcb + ccb0618 commit 42e52f9Copy full SHA for 42e52f9
algorithms/linkedListCycle/linkedListCycle.cpp
@@ -21,24 +21,12 @@
21
*/
22
23
bool hasCycle(ListNode *head) {
24
- ListNode* p1;
25
- ListNode* p2;
26
-
27
- if (head==NULL) return false;
28
- p1=head;
29
- p2=head;
30
31
- while (p1!=NULL && p2!=NULL){
32
33
- p1=p1->next;
34
35
- if (p2->next == NULL) return false;
36
37
- p2=p2->next->next;
38
39
- if (p1==p2) return true;
40
- }
41
42
- return false;
43
44
-}
+ if (head==NULL || head->next==NULL) return false;
+ ListNode* fast=head;
+ ListNode* slow=head;
+ do{
+ slow = slow->next;
+ fast = fast->next->next;
+ }while(fast != NULL && fast->next != NULL && fast != slow);
+ return fast == slow? true : false;
+}
0 commit comments