Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
使用额外空间,hash保存访问过的节点
public ListNode detectCycle(ListNode head)
{
HashSet<ListNode> hashset=new HashSet<>();
if(head==null||head.next==null)
return null;
hashset.add(head);
ListNode node=head.next;
while(node!=null)
{
if(!hashset.contains(node))
{
hashset.add(node);
node=node.next;
}
else {
return node;
}
}
return null;
}
不使用额外空间
https://discuss.leetcode.com/topic/27868/concise-java-solution-based-on-slow-fast-pointers
http://blog.sina.com.cn/s/blog_6f611c300101fs1l.html
首先我们看下面这张图:
设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
扩展问题
3. 如何将有环的链表变成单链表(解除环)?
4. 如何判断两个单链表是否有交点?如何找到第一个相交的节点?
3. 在上一个问题的最后,将c段中Y点之前的那个节点与Y的链接切断即可。
4. 如何判断两个单链表是否有交点?先判断两个链表是否有环,如果一个有环一个没环,肯定不相交;如果两个都没有环,判断两个列表的尾部是否相等;如果两个都有环,判断一个链表上的Z点是否在另一个链表上。
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (slow == fast) {
while (head != slow) {
head = head.next;
slow = slow.next;
}
return slow;
}
}
return null;
}