Skip to content

Latest commit

 

History

History
28 lines (28 loc) · 689 Bytes

142环形链表II.md

File metadata and controls

28 lines (28 loc) · 689 Bytes
  1. 快慢指针,快指针走2,慢指针走1
  2. 相遇后慢指针回到head,两个指针同时走1,再次相遇点则是环起点
  3. 如没有相遇则最后返回null
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    slow, fast := head, head
    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
        if slow == fast {
            slow = head
            for slow != fast {
                slow = slow.Next
                fast = fast.Next
            }
            return slow
        }
    }
    return nil
}