题解 | #判断链表中是否有环(哈希表)#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <cstddef>
class Solution {
  public:
    bool hasCycle(ListNode* head) {
        ListNode* plist = head;
        map<ListNode*, int> m;
        int i = 0;
        
        while (plist != nullptr) {
            auto it = m.find(plist);
            m.insert(pair<ListNode*, int>(plist, i));
            if(it != m.end()){
                return true;
            }
            plist = plist->next;
        }
        return false;
    }
};
哈希表的查找

 查看4道真题和解析
查看4道真题和解析