手写代码:怎么判断链表有环,怎么找环节点
参考回答:
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; }