天天看點

LeetCode_142. Linked List Cycle II

題目描述:

LeetCode_142. Linked List Cycle II
/**
 * 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;
        vector<ListNode*> res;
        ListNode* p=head;
        while(p){
            vector<ListNode*>::iterator it=find(res.begin(),res.end(),p);
            if(it==res.end()){
                res.push_back(p);
                p=p->next;
            }
            else
                return p;
        }
        return NULL;
    }
};      
/**
 * 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) {
        ListNode* meetNode=meetingNode(head);
        if(meetNode==NULL)
            return NULL;
        ListNode* p=meetNode->next;
        int count=1;
        while(p!=meetNode){
            count++;
            p=p->next;
        }
        ListNode *fast=head;
        ListNode *slow=head;
        while(count--){
            fast=fast->next;
        }
        while(slow!=fast){
            slow=slow->next;
            fast=fast->next;
        }
        return slow;
    }
    //查找環中節點個數
    ListNode *meetingNode(ListNode* pNode){
        if(pNode==NULL)
            return NULL;
        ListNode* slow=pNode;
        ListNode* fast=slow->next;
        if(fast==NULL)
            return NULL;
        while(fast){
            if(fast==slow)
                return fast;
            slow=slow->next;
            fast=fast->next;
            if(fast)
                fast=fast->next;
        }
        return NULL;
    }
};      

繼續閱讀