- 问题描述
判断链表是否有环,有环则返回首个环节点,无环则返回为空。 - 解决方案
快慢指针,快走空,肯定无环,否则,快慢指针相遇后,快回到头节点,然后重新走,相遇即首个环节点。
public static Node isLoop(Node head){
if(head == null)
return null;
Node slow = head;
Node fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
break;
}
if(fast.next == null || fast.next.next == null)
return null;
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}