LeetCode每日一题 (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