链表带环问题

来源:互联网 发布:最好的网络电话软件 编辑:程序博客网 时间:2024/05/16 01:32

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、求环的长度

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

原创粉丝点击