leetcode每日一道(9):判斷給定的鏈表中是否有環

題目描述

判斷給定的鏈表中是否有環
擴展:
你能給出不利用額外空間的解法麼?

思路

快慢指針

代碼

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head)
            return 0;
        auto fast = head, slow = head;
        while(fast&&fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if (fast == slow)
                return 1;
        }
        return 0;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章