LeetCode One Question of the Day (36) 141. Circular Linked List (Finding Cycle: Fast and Slow Pointer)

141. Circular Linked List


Insert picture description here
Insert picture description here
Insert picture description here


Mark the visited nodes:

/**
 * 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==nullptr) return false;
        while(head->next!=nullptr){
    
    
            if(head->next->val==100001) return true;
            else{
    
    
                head->val=100001;
                head=head->next;
            }
        }
        return false;
    }
};

Insert picture description here


Speed ​​pointer:

class Solution {
    
    
public:
    bool hasCycle(ListNode* head) {
    
    
        if (head == nullptr || head->next == nullptr) {
    
    
            return false;
        }
        ListNode* slow = head;
        ListNode* fast = head->next;
        while (slow != fast) {
    
    
            if (fast == nullptr || fast->next == nullptr) {
    
    
                return false;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        return true;
    }
};

Insert picture description here


Guess you like

Origin blog.csdn.net/qq_45021180/article/details/108988046