see-142. Linked List Cycle II

本文介绍了一种高效的链表环检测方法,通过快慢指针确定链表是否存在环及环的起始位置。首先使用快慢指针法判断链表是否包含环并找到首次相遇点,接着计算环的具体长度,最后确定环的起始节点。

判断链表中是否有环,以及环开始的节点:

第一步,利用快慢指针法,判定是否有环,并返回快慢指针相遇的节点;

第二步,从快慢指针相遇的节点出发,继续单步遍历链表,记录单步执行次数,当再次回到该相遇节点时,单步遍历次数即为环的长度;

第三步,沿用快慢指针法,快指针先走环长度的步数,之后,快慢指针继续单步遍历,快慢指针相遇的节点即为环的开始节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *flag=hasCycle(head); //the meeting node
        
        if(flag==NULL)
            return NULL; // no cycle
        
        ListNode *link=flag->next;;
        int res=1;
        while(link!=flag)
        {
            res++;
            link=link->next;
        }  // res means the length of the cycle
        
         ListNode *low=head;
         ListNode *fast=head;
         for(int i=0;i<res;i++)
             fast=fast->next; //fast goes res steps 
        
        while(low!=fast)
        {
            low=low->next;
            fast=fast->next;
        } //the meeting node refers to the beginning node of the cycle
        return low;
    }
    
    ListNode *hasCycle(ListNode *head)
    {
        if(head==NULL)
            return NULL;  // no cycle
        
        ListNode *low=head;
        ListNode *fast=head;
        
        while(low!=NULL&&fast!=NULL)
        {
            low=low->next;  // one step
            
            for(int i=1;i<3;i++)
            {
                if(fast==NULL)
                    return NULL;
                else
                {
                    fast=fast->next;
                }
            }  // two steps
            
            if(low==fast)
                return low;
        }
        
        return NULL;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值