题目
https://codefun2000.com/ide/P4104?pset=zijie
思路
https://sprintzerzz.github.io/algorithm-visualization/codefun2000/P4104-Linked-List-Cycle/
code(ACM)
java
import java.util.*;
class Main {
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
}
static Node detectCycle(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// 相遇说明有环
if (slow == fast) {
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// 构造链表
Node dummy = new Node(-1);
Node tail = dummy;
for (int i = 0; i < n; i++) {
Node cur = new Node(sc.nextInt());
tail.next = cur;
tail = cur;
}
// 读取入环位置
int pos = sc.nextInt();
// 只有 pos != -1 才构造环
if (pos != -1) {
Node cur = dummy.next;
for (int i = 0; i < pos; i++) {
cur = cur.next;
}
tail.next = cur;
}
// 判断是否有环
Node cycle = detectCycle(dummy.next);
if (cycle == null) {
System.out.print(-1);
} else {
// 寻找入环节点下标
Node cur = dummy.next;
int index = 0;
while (cur != cycle) {
cur = cur.next;
index++;
}
System.out.print(index);
}
}
}