153

问答题 153 /393

手写代码:怎么判断链表有环,怎么找环节点

参考答案

参考回答:

判断是否有环以及环节点
public class Solution {
ListNode EntryNodeOfLoop(ListNode h){
if(h == null || h.next == null)
return null;
ListNode slow = h;
ListNode fast = h;
while(fast != null && fast.next != null ){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode p=h;

ListNode q=slow;//相当于让q指向了m1

while(p != q){
p = p.next;
q = q.next;
}
if(p == q)
return q;
}
}
return null;
}