Advertisement
yragi_san

Linked List Cycle

Mar 18th, 2023
663
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  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.         ListNode *conejo = NULL;
  13.         ListNode *tortuga = NULL;
  14.         conejo = head;
  15.         tortuga = head;
  16.         bool firstTime = true;
  17.         while(conejo && tortuga){
  18.             if(conejo == tortuga && !firstTime)return true;
  19.             firstTime = false;
  20.             tortuga = tortuga->next;
  21.             conejo = conejo->next;
  22.             if(conejo) conejo = conejo->next;
  23.             else return false;
  24.         }
  25.         return false;
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement