0
点赞
收藏
分享

微信扫一扫

力扣142. 环形链表 II

书呆鱼 2022-03-19 阅读 130


思路:

双指针法。1.先判断是否有环:快指针每次比慢指针多走两步,若有环则必会相遇。2.推导得:头结点到环起点的距离=相遇点到环起点的距离


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 //双指针法。1.先判断是否有环:快指针每次比慢指针多走两步,若有环则必会相遇。2.推导得:头结点到环起点的距离=相遇点到环起点的距离
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
      ListNode* slow = head;
      ListNode* fast = head;
      while(fast != nullptr && fast->next != nullptr)//以fast作为循环条件,不能用slow
      {
        
          fast = fast->next->next;//快指针每次走两步
          slow = slow->next;//慢指针每次走一步
          if(slow == fast)//若快指针=慢指针,则有环
          {
              ListNode* cur = head;
              while(cur != slow)//头结点到环起点的距离=相遇点到环起点的距离
              {
                  cur = cur->next;
                  slow = slow->next;
              }
              return cur;

          }     
      } 
      return NULL;
    }
};

 

举报

相关推荐

0 条评论