classSolution{ public ListNode addTwoNumbers(ListNode l1, ListNode l2){ ListNode head = new ListNode(0); ListNode p = head; ListNode pre = p; int temp;
publicclassSolution{ publicbooleanhasCycle(ListNode head){ Set<ListNode> container = new HashSet<>();
while (head != null) { if (container.contains(head)) { returntrue; } container.add(head); head = head.next; }
returnfalse; } }
Put each ListNode pointer into the Set container. Because every pointer is unique, we just to judge if there’s a pointer’s address we scan has already contained in Set.
This is a nice solution to have a head pointer, which means we haven’t to modified current temp.val and register a new object on the temp.next. Also we needn’t to care whether l1 or l2 is null