天天看點

LeetCode_141. Linked List Cycle

題目描述:

LeetCode_141. Linked List Cycle
/**
 * 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;
        vector<ListNode*> visited;
        ListNode* p=head;
        while(p){
            vector<ListNode*>::iterator it=find(visited.begin(),visited.end(),p);
            if(it==visited.end()){
                visited.push_back(p);
                p=p->next;
            }else{
                return true;   
            }
        }
        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 *fast,*slow;
        fast=slow=head;
        if(fast->next==NULL||fast->next->next==NULL)//一個節點或兩個節點
            return false;
        while(fast){
            slow=slow->next;
            fast=fast->next;
            if(fast!=NULL)//在移動兩次的時候必須要判斷第一次移動後是否是NULL
                fast=fast->next;
            if(fast==slow)
                return true;
        }
        return false;
    }
};      

繼續閱讀