題意:
給定一個鏈表,判斷這個鏈表是否有環
思路:
設定快慢指針,快指針一次走兩步,慢指針一次走一步,如果快指針到達NULL就代表無環,一旦快指針與慢指針相等那麼就代表有環
/** * 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) return false; ListNode *fast,*slow; fast = slow = head->next; while(fast!=NULL&&fast->next!=NULL) { fast = fast->next->next; slow = slow->next; if(fast==slow) return true; } return false; } };