leetcode 142 环形链表 II

简介

容易想到的方法就是 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;
    }
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14840415.html