package com.kk.test;
import java.util.ArrayList;
import java.util.List;
public class Node {
private int value;
private Node nextNode;
public Node() {
}
public Node(int value) {
this.value = value;
}
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
//打印链表
public void printNode(){
Node node = this;
while (true){
System.out.print(node.value+"->");
node = node.getNextNode();
if (node == null){
System.out.println();
break;
}
}
}
//判断是否有环
public boolean isCycle(){
List<Node> list = new ArrayList<>();
Node node = this;
while (true){
if (list.contains(node)){
return true;
}
list.add(node);
node = node.getNextNode();
if (node == null){
return false;
}
}
}
}
示例
public static void main(String[] args) {
Node last = new Node(99);
Node node = new Node(1, new Node(2, new Node(3, new Node(4, last))));
//last.setNextNode(node);
//node.printNode();
System.out.println(node.isCycle());
}