链表带环问题

1、判断链表是否带环

基本思路:定义两个指针,一个快指针,一个慢指针,快指针一次走两步,慢指针一次走一步,当两个指针重合的时候,说明该链表是带环的,当快指针为空或者快指针的下一个节点为空,说明是不带环的。
代码实现

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode *head) {
        // write your code here
        if(head==NULL || head->next==NULL)
        {
            return false;
        }
        ListNode* fast=head;
        ListNode* slow=head;
        while(fast && fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;

            if(fast==slow)
            {
                return true;
            }
        }
        return false;
    }
};
2、求环的入口点

基本思路:
这里写图片描述

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    ListNode *detectCycle(ListNode *head) {
        // write your code here
        if(!head || !head->next)
        {
            return NULL;
        }

        ListNode* fast=head;
        ListNode* slow=head;
        ListNode* meet=NULL;
        while(fast && fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
            {
                meet=fast;
                slow=head;
               while(meet!=slow)
             {   
                meet=meet->next;
                slow=slow->next;
             }
                return slow;
            }

        }


        //没有环
        return NULL;

    }
};
3、求环的长度

求环的长度的前提就是先求出快指针的慢指针相遇的节点,然后将该相遇的节点记录下来,让一个新的指针指向该相遇的节点,然后让新的指针一直往后走,当新指针再次走到相遇节点时就可以求出环的长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值