LeetCode 141, 142. Linked List Cycle I+II

判断链表有没有环,用Floyd Cycle Detection算法,用两个快慢指针。

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

142是141的进阶,需要额外判断环的起点。

详见 https://leetcode.com/problems/linked-list-cycle-ii/solution/ 中的推导,不过里面应该是 F=(n-1)(a+b)+b,因此从head和相遇点开始同时走,一定会在循环起点相遇。

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if (!head) return NULL;
        ListNode *slow, *fast;
        slow = fast = head;
        do{
            if (!fast || !fast->next) return NULL;
            slow = slow->next;
            fast = fast->next->next;
        }while(slow!=fast);
        
        ListNode *p=head, *q=slow;
        while(p!=q){
            p = p->next;
            q = q->next;
        };
        return p;    
    }
};

猜你喜欢

转载自www.cnblogs.com/hankunyan/p/9126249.html
今日推荐