判断单链表是否有环,如果有环的话,具体再有环的节点是哪个?
static class Node { private Node next; private int val; public Node(Node next, int val) { this.next = next; this.val = val; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getVal() { return val; } public void setVal(int val) { this.val = val; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; return val == node.val && Objects.equals(next, node.next); } } public static void main(String[] args) { Node node1 = new Node(null, 1); Node node2 = new Node(node1, 2); Node node3 = new Node(node2, 3); Node node4 = new Node(node3, 4); Node node5 = new Node(node4, 5); Node node6 = new Node(node5, 6); Node node7 = new Node(node6, 7); Node node8 = new Node(node7, 8); Node tail = new Node(node8, 9); node1.setNext(node4); Node slow = tail; Node fast = tail; int count = 1; slow = slow.next; fast = fast.next.next; while (slow.val != fast.val) { count++; slow = slow.next; fast = fast.next.next; } System.out.println(JSON.toJSONString(slow.val) + ";count=" + count); slow = tail; slow = slow.next; fast = fast.next; while (slow.val != fast.val) { slow = slow.next; fast = fast.next; } System.out.println(JSON.toJSONString(slow.val)); }