方式一
基本思想,就是定义两个临时节点,分别指向链表的头节点,然后一个执行大循环,一个执行小循环,当出现两个节点引用相同的情况时,则说明出现了环。
static class Node{
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
private static boolean hasLoop(Node node) {
Node node1 = node;
Node node2 = node.next;
while (node2 != null) {
if (node1 == node2) return true;
// 继续迭代,temp1每次向后走一步,temp2每次向后走两步
node1 = node1.next;
node2 = node2.next.next;
if (node2 == null) return false;
}
// 如果temp2位null,说明链表元素只有一个节点,一个节点认为是存在环
return true;
}
方式二
如果依靠HashMap或者HashSet集合来实现。HashSet是因为元素不能重复,而HashMap可以通过将Node作为key来实现,如果当前key存在value,说明已经出现了两次,则出现了环。
private static boolean hasLoop1(Node head) {
if (head == null) {
return true;
}
Node next = head.next;
HashSet<Node> hashSet = new HashSet<>();
while (next != null) {
if (hashSet.contains(next)) return true;
hashSet.add(next);
next = next.next;
if (next == null) return false;
}
return true;
}
private static boolean hasLoop2(Node head) {
Node next = head;
HashMap<Node, Node> map = new HashMap<>();
while (next != null) {
if (map.get(next) != null) return true;
map.put(next, next);
next = next.next;
if (next == null) return false;
}
return true;
}
网友评论