题解 | #判断链表中是否有环#

判断链表中是否有环

http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

哈希方式

class Solution {
public:
    bool hasCycle(ListNode *head) {
        unordered_map<ListNode *, bool> m;
        while(head){
            if(m.find(head) != m.end())
                return true;
            m[head] = true;
            head = head->next;
        }
        return false;
    }
};

快慢指针

class Solution {
public:
    bool hasCycle(ListNode *head) {
        //快慢指针
        if(!head) return false;
        ListNode * slow = head;
        ListNode * fast = head->next;

        while(slow != fast && slow && fast){
            slow = slow->next;
            fast = fast->next;
            if(!fast) return false;
            fast = fast->next;
        }
        if(slow == fast)
            return true;
        return false;
    }
};
全部评论

相关推荐

02-15 15:29
青岛大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务