leetcode twopointer 141 circular linked list

THE

problem

Insert picture description here

achieve

Ideas

Judge the ring and use the fast or slow pointer to go. The fast pointer moves twice at a time, and the slow pointer moves one grid at a time. If there is a ring, then it must meet, and when it meets, it is time to exit.

  • define fast , slow
  • while(fast!&&fast.next!==NULL)
    • fast = fast +2
    • slow = slow +1
    • if(fast ==slow ) return true
  • return false;

Summary and reflection

  1. Pay attention to how next.next guarantees that it does not cross the boundary.

Code

class Solution {
    
    
public:
   bool hasCycle(ListNode *head) {
    
    
       ListNode* fast = head;
       ListNode* slow = head;
       while(fast && fast->next){
    
      // make sure next is not null that make next.next is not null. 
           fast = fast->next->next;
           slow = slow->next;
           if(fast == slow ) return true;
       }
       return false;
   }
};

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114043928