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实现)
最新推荐文章于 2022-05-13 19:35:15 发布