Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
public ListNode detectCycle(ListNode head) {
HashMap<ListNode, Integer> nodeIdMap = new HashMap<>();
int id = 0;
for (;;) {
if (head == null) return null;
Integer ID = nodeIdMap.get(head);
if (ID != null) {
return head;
} else {
nodeIdMap.put(head, id++);
}
head = head.next;
}
}
TODO: solve it without using extra space