节点类
@Data
public class Node {
private Object data;
private Node next;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}
实现类
package day04;
public class Test05 {
public static void main(String[] args) {
Node lastNode = new Node(55);
Node node4 = new Node(44,lastNode);
Node node3 = new Node(33,node4);
Node node2 = new Node(22,node3);
Node headNode = new Node(11,node2);
lastNode.setNext(node3);
boolean flag = isCycle(headNode);
System.out.println(flag);
}
public static boolean isCycle(Node headNode){
if (headNode == null)
return false;
Node fast = headNode;
Node slow = headNode;
while (fast != null && fast.getNext() != null){
fast = fast.getNext().getNext();
slow = slow.getNext();
if (fast == slow)
return true;
}
return false;
}
}
|