LeetCode今日の1つの質問(36)141。循環リンクリスト(検索サイクル:高速および低速ポインター)

141.循環リンクリスト


ここに画像の説明を挿入
ここに画像の説明を挿入
ここに画像の説明を挿入


訪問したノードをマークします。

/**
 * 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;
    }
};

ここに画像の説明を挿入


スピードポインター:

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;
    }
};

ここに画像の説明を挿入


おすすめ

転載: blog.csdn.net/qq_45021180/article/details/108988046