NC3 链表中环的入口结点
描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
输入描述:
输入分为2段,第一段是入环前的链表部分,第二段是链表环的部分,后台将这2个会组装成一个有环或者无环单链表
返回值描述:
返回链表的环的入口结点即可。而我们后台程序会打印这个节点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
if(pHead == null || pHead.next == null){
return null ;
}
ListNode slow = pHead , fast = pHead.next ;
while(slow != fast){
if(fast == null || fast.next == null){
return null ;
}
slow = slow.next ;
fast = fast.next.next ;
}
slow = pHead ;
while(slow != fast.next ){
fast = fast.next ;
slow = slow.next ;
}
return slow ;
}
}
这篇博客探讨了一种在单链表中检测和找到环的入口节点的算法。通过使用快慢指针,当快指针首次遇到慢指针时,它们相遇于环内。然后,从头节点重新开始,用慢指针继续遍历,直到再次与快指针相遇,那个节点即为环的入口。这种方法确保了在链表无环时返回null。
903

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



