leetcode twopointer 141 环形链表

O

问题

在这里插入图片描述

实现

思路

判断有环采用快慢指针去走。 快指针一次走两次, 慢指针一次走一个格子,如果有环那么一定是会相遇的,相遇的时候就是退出的时候。

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

总结与反思

  1. 注意考虑next.next 如何保证不越界。

代码实现

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;
   }
};

猜你喜欢

转载自blog.csdn.net/liupeng19970119/article/details/114043928
今日推荐