链表是否有环java实现



/**
 * @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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值