golang leetcode 环状链表II

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    if head==nil{
        return nil
    }
    //快慢指针
    slow:=head
    fast:=head
    for fast!=nil&&fast.Next!=nil{
        slow = slow.Next
        fast = fast.Next.Next
        if fast==slow{
            tmp:=head

            for tmp!=slow{
                tmp = tmp.Next
                slow = slow.Next
            }
            return tmp
        }
    }
    return nil
}

 

posted @ 2021-01-07 13:52  海拉尔  阅读(56)  评论(0编辑  收藏  举报