1. 程式人生 > >leetcode 141. Linked List Cycle (easy)

leetcode 141. Linked List Cycle (easy)

Given a linked list, determine if it has a cycle in it. 

 

快的節點終究會追趕上慢的節點,除非沒有形成環,快節點會提前越界

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode* slow=head;
        ListNode* fast=head;
        while(fast->next&&fast->next->next){
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
                return 1;
        }
        return 0;
    }
};