[LeetCode 141,LeetCode 142]链表是否有环

[LeetCode 141,LeetCode 142]C++实现判断链表是否有环,及环的入口位置

1-a: 判断是否有环
https://leetcode-cn.com/problems/linked-list-cycle/(LeetCode 141)

//方法1、利用STL中set

class Solution {
public:
    bool hasCycle(ListNode *head) {
        set<ListNode*>s;
        while(head){
            if(s.find(head)==s.end()){
                s.insert(head);
                head=head->next;
            }
            else
                return true;
        }
        return NULL;
    }
};
//方法2、快慢指针在环上相遇

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* pFast=head;
        ListNode* pSlow=head;

        do{
            if(pFast){
                pSlow=pSlow->next;
                pFast=pFast->next;
            }
            if(pFast)
                pFast=pFast->next;
            if(!pFast)
                return false;
        }while(pFast!=pSlow);
        if(pFast){
            return true;
        }
        else
            return false;
    }
};

1-b:判断环的入口位置
https://leetcode-cn.com/problems/linked-list-cycle-ii/(LeetCode 142)

//方法1、利用set

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<ListNode*>s;
        while(head){
            if(s.find(head)==s.end()){
                s.insert(head);
                head=head->next;
            }
            else
                return head;
        }
        return NULL;
    }
};

//方法2、快慢指针
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == NULL||head->next == NULL)
            return nullptr;

        ListNode* pFast=head;
        ListNode* pSlow=head;

        ListNode* meet=NULL;
        ListNode* ifNULL=head;

        do{
            if(pFast!=NULL){
                pFast=pFast->next;
                pSlow=pSlow->next;
            }
            if(pFast!=NULL)
                pFast=pFast->next;
            if(pFast==NULL){
                return NULL;
            }        
        }while(pFast!=pSlow);//when(pFast==pSlow) break;
        
        while(pSlow!=head&&pSlow){//从相遇位置走,从开始节点走,步速一致,相遇即为环入口节点
            pSlow=pSlow->next;
            head=head->next;
        }
        meet=pSlow;
        return meet;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值