简介

容易想到的方法就是 map , set 之类的.

code

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head == nullptr) return nullptr;
        ListNode *p = head;
        unordered_map<ListNode*, bool> m;
        int index = 0;
        while(p){
            if(m[p]){
                return p; 
            }
            index++;
            m[p] = true;
            p = p->next;
        }
        return nullptr;
    }
};
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode p = head;
        Map<ListNode, Boolean> m = new HashMap<ListNode, Boolean>();
        while(p != null){
            if(m.containsKey(p)){
                return p;
            }
            m.put(p, true);
            p = p.next;
            
        }
        return null;
    }
}
posted on 2021-06-02 10:53  HDU李少帅  阅读(26)  评论(0编辑  收藏  举报