链表面试题 --- 判断单链表是否带环?若带环,求环的长度?求环的入口点?

判断链表是否有环
思路:
定义一个Fast结点一个Slow结点,Fast结点每次是Slow结点走的二倍,如果在Fast == NULL之前 Slow == Fast 就表明单链表带环

int HasListCircle(ListNode* pHead)//判断链表是否有环
{
    assert(pHead);
    ListNode* pFast = pHead;
    ListNode* pSlow = pHead;
    while (pFast && pFast->next)
    {
        pFast = pFast->next->next;
        pSlow = pSlow->next;
        if (pFast == pSlow)
            return 1;
    }
    return 0;

}

求环长度
思路:先找到相遇点,记住相遇点,找一个节点从相遇点开始走,并记录走的结点个数,直到再次遇到相遇点,此时走过的节点个数就是环的长度

ListNode* GetMeetNode(ListNode* pHead)//求相遇点
{
    assert(pHead);
    ListNode* pFast = pHead;
    ListNode* pSlow = pHead;
    while (pFast && pFast->next)
    {
        pFast = pFast->next->next;
        pSlow = pSlow->next;
        if (pFast == pSlow)
            return pFast;
    }
    return NULL;

}

int GetCircleLen(ListNode* pMeetNode)//求环的长度
{
    ListNode* pCur = pMeetNode;
    int count = 1;
    if (pMeetNode == NULL)
        return 0;
    while (pCur->next != pMeetNode)
    {
        pCur = pCur->next;
        count++;
    }
    return count;
}

求环的入口点
如图所示
这里写图片描述

ListNode* GetEnterNode(ListNode* pHead, ListNode* pMeetNode)//求环的入口
{
    if (pHead == NULL || pMeetNode == NULL)
        return NULL;
    ListNode* pH = pHead;
    ListNode* pM = pMeetNode;
    while (pH != pM)
    {
        pH = pH->next;
        pM = pM->next;
    }
    return pH;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值