【leetcode】141.(Easy)Linked List Cycle

解题思路:
维护一个map,如果当前节点的下一个节点是已经存在的节点(map中的节点)则链表有循环

提交代码:

class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null)	return false;
        
        Map<ListNode,Boolean> map=new HashMap<>();
        ListNode p=head;
        while(p!=null) {
        	if(map.containsKey(p))	return true;
        	map.put(p, true);
        	p=p.next;
        }
        return false;
    }
}

运行结果:
【leetcode】141.(Easy)Linked List Cycle