leetcode笔记--Linked List Cycle II

来源:互联网 发布:二手双拼域名 编辑:程序博客网 时间:2024/04/29 00:02

题目:难度(Medium)

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
    Can you solve it without using extra space?
Tags:Linked List Two Pointers
Similar Problems:(M) Linked List Cycle (H) Find the Duplicate Number

分析:如果一个链表中存在环,则返回环开始的节点。指针p、q都从head出发,p一次走一步,q一次走2步,用”“龟兔赛跑”算法先判断是否有环,如果确实存在环,p、q一定会在环上某个位置相遇,如下图:


设相遇的位置为r,环路起点为x,环上一点m,那么我们可以知道,从头节点开始走,h-x-r为p走的路线,是p步,h-x-r-m-x-r为q走的路线,是2p步,即r-m-x-r为q走的后半截路线,也是p步,那么路线长度h-x-r = r-m-x-r = p步,那么可得出路线长度h-x = r-m-x =  k步。即若从头节点出发和从r位置同时出发,均走出k步,那么他们一定会相遇,且相遇位置就在x处,即环路开始的位置。

代码实现:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def detectCycle(self, head):        """        :type head: ListNode        :rtype: ListNode        """                if head is None:            return None        if head.next is None:            return None        #p、q都从head出发,p一次走一步,q一次走2步,采用"龟兔赛跑"算法先找到相遇点        #走出第一步后,p在head.next的位置,q在head.next.next的位置        p = head.next        q = p.next        while q is not None:            if p != q:                p = p.next                q = q.next                if q is not None:                    q = q.next            else:                #r为p、q相遇的位置,该位置一定是在环上                r = q                break        if q is None:            return None        else:            #有环            p = head             q = r            while p!=q:                p = p.next                q = q.next            return p


0 0
原创粉丝点击