048_环形链表II

知识点:快慢指针、链表

LeetCode第一百四十二题:https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/

语言:GoLang

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    if head == nil {
        return nil
    }

    noCycle := true
    slow, fast := head, head
    for slow.Next != nil && fast.Next != nil && fast.Next.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next

        if fast == slow {
            noCycle = false
            break
        }
    }

    if noCycle {
        return nil
    }

    fast = head
    for fast != slow {
        slow = slow.Next
        fast = fast.Next
    }

    return fast
}
posted @ 2020-04-05 11:49  Cenyol  阅读(88)  评论(0)    收藏  举报