Java算法_链表循环(LeetCode_Hot100)

题目描述:给你一个链表的头节点 ,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪 指针再次到达,则链表中存在环。为了表示给定链表中的环,评测系统内部使用整数 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。nextpos,如果链表中存在环 ,则返回 。否则,返回 。truefalse

获得更多?算法思路:代码文档,算法解析的私得。

运行效果
在这里插入图片描述

完整代码

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 2 * @Author: LJJ
 * 3 * @Date: 2023/8/1 9:06
 * 4
 */
public class LinkedListCycle {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int val) {
            this.val = val;
            this.next = null;
        }
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;   // No cycle
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

    public static void printLinkedList(ListNode head) {
        Set<ListNode> visited = new HashSet<>();

        ListNode current = head;
        while (current != null) {
            if (visited.contains(current)) {
                System.out.println("链表中存在环,无法完整打印链表。");
                return;
            }

            System.out.print(current.val + " -> ");
            visited.add(current);
            current = current.next;
        }

        System.out.println("null");
    }


    public static void main(String[] args) {
        // 创建链表
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = head.next; // Creating the cycle (5 -> 2)

        // 检查是否是循环链表
        boolean hasCycle = hasCycle(head);

        System.out.println("原始链表:");
        printLinkedList(head);

        if (hasCycle) {
            System.out.println("是循环链表.");
        } else {
            System.out.println("不是循环链表.");
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值