题目描述
给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
输入描述:
输入分为2段,第一段是入环前的链表部分,第二段是链表环的部分,后台会根据第二段是否为空将这两段组装成一个无环或者有环单链表
返回值描述:
返回链表的环的入口结点即可,我们后台程序会打印这个结点对应的结点值;若没有,则返回对应编程语言的空结点即可。
求解思路&实现代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
// 首先先判断是否存在入环节点
public ListNode hasCycle(ListNode pHead){
if(pHead==null) return null;
ListNode fast=pHead;
ListNode slow=pHead;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow) return fast;
}
return null;
}
// 如果存在环的话,此时快指针回到头结点,慢指针在相遇的节点,接下来同时向后移动一个位置,下次相遇的时候就是入环节点
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode root=hasCycle(pHead);
if(root==null) return null;
ListNode fast=pHead;
ListNode slow=root;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return fast;
}
}