package com.spj.algorithm;
/*
*@program:架构师
*@Author:peng
*@Time:2022/4/9 8:36
*
*/
public class _9_CycleLink {
static class ListNode {
int val;
ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode node5 = new ListNode(5, null);
ListNode node4 = new ListNode(4, node5);
ListNode node3 = new ListNode(3 ,node4);
ListNode node2 = new ListNode(2, node3);
ListNode node1 = new ListNode(1, node2);
node5.next=node2;
System.out.println(hasCycle(node1));
}
private static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow=head;
ListNode fast=head.next;
for (;;){
if (slow.val==fast.val)return true;
slow=slow.next;
fast=fast.next.next;
}
}
}
9.环形链表
最新推荐文章于 2023-10-16 00:52:12 发布