public class E23FindEntryFromLoop {
//链表中环的入口节点
private class ListNode{
int value;
ListNode nextNode;
}
public static ListNode entryNodeOfLoop(ListNode head){
if (head == null)
return null;
//判断是否存在环
ListNode loopNode = meetingNode(head);
if (loopNode == null)
return null;
//得到环中节点数量
int count = 1;
ListNode node = loopNode;
while(node.nextNode != loopNode){
loopNode = loopNode.nextNode;
count ++;
}
//找出环的入口节点
ListNode ahead = head;
ListNode behind = head;
for (int i = 0; i < count; i ++)
ahead = ahead.nextNode;
while(ahead != behind){
ahead = ahead.nextNode;
behind = behind.nextNode;
}
return behind;
}
private static ListNode meetingNode(ListNode head){
//判断是否存在环并返回一个处于环中的节点,不存在则返回null
ListNode fast = head;
ListNode slow = head;
fast = fast.nextNode;
while(slow != null && fast != null){
if (slow == fast)
return slow;
slow = slow.nextNode;
fast = fast.nextNode;
if (fast != null)
fast = fast.nextNode;
}
return null;
}
}
链表中环的入口节点(Java实现)
最新推荐文章于 2023-07-25 23:06:42 发布
本文介绍了一种高效算法,用于查找链表中环的入口节点。通过快慢指针判断链表是否存在环,并计算环内节点数,最终确定环的入口节点。此算法适用于计算机科学和数据结构学习。
335

被折叠的 条评论
为什么被折叠?



