首页 > 技术文章 > 判断链表是否又环

lyf-sunicey 2018-08-28 13:46 原文

/**
 * 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 ||head->next == NULL)return NULL;
        ListNode* fast = head;
        ListNode* low = head;
        while(fast && fast->next){
            fast = fast->next->next;
            low = low->next;
            if(fast == low)break;
        }
        
        if(fast != low)return NULL;
        low = head;
        while(1){
            if(fast == low)break;
            low = low->next;
            fast = fast->next;
            
        }
        return low;
    }
};
判断是否有环

/**
 * 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 || head->next == NULL)return false;
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast)return true;
        }
        return false;
    }
};

 

 

 

推荐阅读