码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):142-Linked List Cycle II

时间:2016-05-09 18:26:56      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  https://leetcode.com/problems/linked-list-cycle-ii/


 

题意分析:

  给定一个链表,如果链表有环,返回环的起始位置,否则返回NULL。要求常量空间复杂度。


 

题目思路:

  首先可以用快慢指针链表是否有环。假设链表头部到环起点的距离为n,环的长度为m,快指针每次走两步,慢指针每次走一步,快慢指针在走了慢指针走t步后相遇,那么相遇的位置是(t - n) % m + n=(2*t - n)%m + n,那么得到t%m = 0,所以头部和相遇的位置一起走n步会重新相遇。那么,头部和相遇点再次走,知道相遇得到的点就为起点。


 

代码(python):

技术分享
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return None
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                tmp = head
                while tmp != fast:
                    tmp,fast = tmp.next,fast.next
                return tmp
        return None
                    
View Code

 

[LeetCode]题解(python):142-Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/chruny/p/5474610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!