Linked List Cycle(C++環形鏈表)

解題思路:

(1)設置快慢指針,如果存在環,那麼快的指針最後會追上慢的指針

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章