Floyd判圈法

leetcode141-环形链表
其算法应用龟兔赛跑的思想,使用一个slow和fast指针初始都指向链表第一个节点,slow每次向前走一步,fast向前走两步。如果链表无环,那么fast会先走到NULL节点。如果有环,那么当slow和fast都进入环的时候,由于fast比slow走的快,fast总会追上slow。C++代码如下:
写法一:快慢指针不在同一起点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode* slow=head,*fast=head->next;
        while(fast!=NULL && fast->next!=NULL){
            if(slow==fast)
                return true;
            else{
                slow=slow->next;
                fast=fast->next->next;
            }
        }
        return false;
    
    }
};


写法二:快慢指针在同一起点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode* slow=head,*fast=head;
        while(true){		//把跳出循环的逻辑写在循环体内部会简单一点
            slow=slow->next;
            fast=fast->next;
            if(fast==NULL) 
                return false;
            fast=fast->next;
            if(fast==NULL)
                return false;
            if(slow==fast)
                return true;
        }
        return false;
    
    }
};

注意要判断两次fast是否为空.

leetcode142-环形链表 II
假设已经判断出有环,寻找入环节点的原理如下:
image

注意这个原理中快慢指针起始位置一定要在同一位置,如果慢指针在head,快指针在head->next,二者走的路程就不满足二倍关系

/**
 * 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) {
        if(head==NULL)
            return NULL;
        ListNode*slow=head,*fast=head;
        while(true){
            slow=slow->next;
            if(fast->next==NULL)
                return NULL;
            else
                fast=fast->next->next;
            if(fast==NULL)
                return NULL;
                
            if(slow==fast){
                ListNode*tmp=head;
                while(tmp!=slow){
                    tmp=tmp->next;
                    slow=slow->next;
                }
                return tmp;
            }    
        }
        return NULL;
    }
};
posted @   陈陈相因的陈  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示