题目描述:给你一个链表的头节点 ,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪 指针再次到达,则链表中存在环。为了表示给定链表中的环,评测系统内部使用整数 来表示链表尾连接到链表中的位置(索引从 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("不是循环链表.");
}
}
}