/**
* @author mccrea
* @version 1.0
* @description: 单链表中是否有环
* @date 2020/9/11 22:52
*/
public class SingleListCircleDemo {
public static void main(String[] args) {
SingleListCircle singleListCircle = new SingleListCircle();
CircleNode circleNode1 = new CircleNode(1);
CircleNode circleNode2 = new CircleNode(2);
CircleNode circleNode3 = new CircleNode(3);
CircleNode circleNode4 = new CircleNode(4);
CircleNode circleNode5 = new CircleNode(5);
CircleNode circleNode6 = new CircleNode(6);
singleListCircle.addNode(circleNode1);
singleListCircle.addNode(circleNode2);
singleListCircle.addNode(circleNode3);
singleListCircle.addNode(circleNode4);
singleListCircle.addNode(circleNode5);
singleListCircle.addNode(circleNode6);
System.out.println("第一次链表是否有环? :" + singleListCircle.haveCircle());
singleListCircle.addNode(circleNode3);
System.out.println("第二次链表是否有环? :" + singleListCircle.haveCircle());
}
}
/**
* @description: 定义节点
* @author mccrea
* @date 2020/9/11 22:41
* @version 1.0
*/
class CircleNode {
/**
* 数据
*/
public int data;
/**
* 下一个节点
*/
public CircleNode next;
/**
* 构造函数
*
* @param data 传入的数据
*/
public CircleNode(int data) {
this.data = data;
}
@Override
public String toString() {
return "CircleNode{" +
"data=" + data +
'}';
}
}
/**
* @description: 单链表操作结点
* @author mccrea
* @date 2020/9/11 22:56
* @version 1.0
*/
class SingleListCircle {
/**
* 默认有个头节点,不参与任何增删改查操作
*/
private CircleNode head = new CircleNode(0);
/**
* 增加节点
*
* @param node 新增的节点
*/
public void addNode(CircleNode node) {
// 定义一个指针
CircleNode temp = head;
// 指针后移找到尾节点
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
/**
* @description: 判断单链表是否有环
* @author mccrea
* @date 2020/9/11 22:58
* @version 1.0
*/
public boolean haveCircle() {
// 链表为空,判断是否有环无意义
if (head.next == null) {
throw new RuntimeException("链表为空!");
}
// 快指针
CircleNode fast = head;
// 慢指针
CircleNode slow = head;
while (slow != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}