public class Demo {
public static void main(String[] args) {
// 链表中环的检测
Node node = getNode(10, true);
boolean checkRing = checkRing(node);
System.out.println(checkRing);
}
// 环检测
private static boolean checkRing(Node node) {
Node fast = node;
Node show = node;
while (fast != null && fast.next != null) {
fast = fast.next.next;
show = show.next;
if (fast == show) {
return true;
}
}
return false;
}
// 获取普通链表
private static Node getNode(Integer n, boolean ring) {
Node head = null;
Node node = null;
for (int i = 1; i <= n; i++) {
Node next = new Node(i);
if (node == null) {
node = next;
head = next;
} else {
node.next = next;
node = next;
}
}
// 是否造环
if (ring) {
node.next = head;
}
return head;
}
static class Node {
public Node next;
public Integer value;
public Node(Integer value) {
this.value = value;
}
}
}
数据结构与算法(二)——链表中环的检测
最新推荐文章于 2023-09-12 20:01:06 发布