leetcode: Linked List Cycle II

来源:互联网 发布:stm32编程环境 编辑:程序博客网 时间:2024/06/08 15:13

这道题在1的基础上要我们找到环的起点。   由于环的起点不一定就是链表的起点,所以我们设链表起点到环起点距离为x,慢指针在环中走了y,慢指针走到环起点距离为z。

那么慢指针走了x+y,快指针走了x+y+z+y。   快指针走的距离是慢指针的两倍,因而得到x=z。  即快慢指针第一次相遇的时候链表起点到环起点的距离等于相遇节点到环起点的距离。   因而两个while即可。


/** * 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 res =null;        boolean is=false;        if( head==null )        {            return res;        }        ListNode st1=head,st2=head;        while( st1.next!=null && st2.next!=null && st2.next.next!=null )        {            st1=st1.next;            st2=st2.next.next;            if( st1==st2 )            {                res=st1;                break;            }        }        if(res==null)        {            return res;        }        st1=head;        while(st1!=st2)        {            st1=st1.next;            st2=st2.next;        }        return st1;            }}


0 0
原创粉丝点击