LeetCode 141:环形链表

方法一:利用链表类问题中最常用的快慢指针方法

(2t-(p-1))%q == (t-(p-1))%q,这种情况下会判定有环。

注意:在fast->next为null时,必须在else中将它也置为null,否则链表长度为偶数时跳不出循环,最后一定会返回true!

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;   //bug1:没有检测输入指针是否为null
        ListNode* fast = head->next;
        ListNode* slow = head;
        while(fast) {
            slow = slow->next;
            if(fast->next) {
                fast = fast->next->next;
            }else{
                fast = fast->next;  //bug2:在fast->next为null时,必须在else中将它也置为null,否则链表长度为偶数时跳不出循环,最后一定会返回true
            }
            if(slow == fast) return true;
        }
        return false;
    }
};

更简洁的写法: 

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

方法二:使用额外空间,哈希表:unordered_set(与unoreder_map在实现/使用上的区别?)

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_set <ListNode*>  visited;
        while(head) {
            if(visited.count(head)) return true;
            visited.insert(head);
            head = head->next;
        }
        return false;
    }
};
发布了97 篇原创文章 · 获赞 11 · 访问量 2491

猜你喜欢

转载自blog.csdn.net/chengda321/article/details/102633454
今日推荐