1. 程式人生 > 實用技巧 >連結串列是否有環

連結串列是否有環

1-a (true or false)
[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 (return Pos)
[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 meet;
        }        
    }while(pFast!=pSlow);//when(pFast==pSlow) break;
    
    while(pSlow!=head&&pSlow){//從相遇位置走,從開始節點走,步速一致,相遇即為環入口節點
        pSlow=pSlow->next;
        head=head->next;
    }
    meet=pSlow;
    return meet;
}

};