import java.util.*;
public class P139_EntryNodeOfLoop {
static class ListNode<T> {
T val;
ListNode<T> next;
ListNode(T val) {
this.next = null;
this.val = val;
}
@Override
@SuppressWarnings("all")
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("[");
for (ListNode cur = this; ; cur = cur.next) {
if (cur == null) {
ret.deleteCharAt(ret.lastIndexOf(" "));
ret.deleteCharAt(ret.lastIndexOf(","));
break;
}
ret.append(cur.val);
ret.append(", ");
}
ret.append("]");
return ret.toString();
}
}
private static ListNode entryNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return null;
}
ListNode fast = pHead;
ListNode slow = pHead;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast.val == slow.val) {
fast = pHead;
while (fast.val != slow.val) {
fast = fast.next;
slow = slow.next;
}
}
if (fast.val == slow.val) {
return slow;
}
}
return null;
}
private static ListNode entryNodeOfLoop2(ListNode pHead) {
if (pHead == null || pHead.next == null) {
return null;
}
ListNode fast = pHead.next;
ListNode slow = pHead;
while (fast != null) {
slow.next = null;
slow = fast;
fast = fast.next;
}
return slow;
}
private static ListNode entryNodeOfLoop3(ListNode pHead) {
Map map = new HashMap();
while (pHead.next != null) {
if (!map.containsValue(pHead)) {
map.put(pHead, pHead);
pHead = pHead.next;
} else {
return pHead;
}
}
return null;
}
public static void main(String[] args) {
ListNode<Integer> node1 = new ListNode<>(1);
ListNode<Integer> node2 = new ListNode<>(2);
ListNode<Integer> node3 = new ListNode<>(3);
ListNode<Integer> node4 = new ListNode<>(4);
ListNode<Integer> node5 = new ListNode<>(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node3;
System.out.println("entryNodeOfLoop(node1) = " + entryNodeOfLoop3(node1));
}
}