null
.
Follow up:
Can you solve it without using extra space?
给定链表,若存在环返回环的起点,否则返回null。
貌似网易面试的时候曾经出过类似问题,但网易只要求判断是否存在环。具体方法为定义两个指针one 、two遍历链表,one一次扫描一个节点,two一次扫描两个节点。
若存在环最终one 和two一定会相遇。我称之为步差法,假设one访问到环的起始节点Y时two在按顺时针离Y c个节点处Z,则在经过c次前进后one、two一定会相遇于W。此时one走了c步<Y,W> 长为c,而two走过了2C步比one多走C步刚好赶上one与之重合。
步差法就是在存在回路的情况下,不同指针每步相差K个节点,则走的快的最终会追上走的慢的,假设走了M步则他们相差K*M个节点。
本题是上述的扩展。可知当one和two在z点相遇时one走过a+b各节点,two走过a+b+c+b各节点,二two走过的路程是one的两倍即2*(a+b)=a+b+c+b,可知a=c。
所以本体解法,只需先让one、two以各自步长走,当one、two相遇时,two步长变为1,one从头X开始走则one、two再次相遇的点必定是Y点。
贴一下我的代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode one = head;
ListNode two = head;
while(two != null)
{
one = one.next;
two = two.next;
if(two != null)two = two.next;
if(one == two)break;
}
if(two == null)return null;
one = head;
while(true)
{
if(one == two)return one;
one = one.next;
two = two.next;
}
}
}