package com.doubleLinked; public class CirCularLinked { /** * 检测是否为圆形链表 * @param head 传入的链表头结点 * @return */ public static ListNode detectLink(ListNode head){ ListNode slow = head; ListNode fast = head; boolean isCircle = false; while(!isCircle && fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; isCircle = slow == fast; } if(!isCircle){ return null; } ListNode p = head; while(p != slow){ p = p.next; slow = slow.next; } return p; } public static void main(String[] args) { ListNode head = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); head.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n2; ListNode p = detectLink(head); System.out.println(p.data + " "); } }
检测圆形链表的入口
最新推荐文章于 2024-09-10 10:21:38 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)