lintcode练习-103. 带环链表 II

103. 带环链表 II

给定一个链表,如果链表中存在环,则返回到链表中环的起始节点,如果没有环,返回null。

样例

给出 -21->10->4->5, tail connects to node index 1,返回10

挑战

不使用额外的空间

解题思路:

1、定义一个快慢指针,

2、如果链表无环,那么fast一定会遇到终点,返回none。

3、如果链表有环,则两个链表一定会相遇,当两个相遇以后,fast重新回到head的位置,slow不动。然后fast指针和slow指针每次都移动一步,继续遍历

4、当两个指针再次相遇时,就是第一个入环的结点。

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: The first node of linked list.
    @return: The node where the cycle begins. if there is no cycle, return null
    """
    def detectCycle(self, head):
        # write your code here
        if head is None or head.next is None or head.next.next is None:
            return None
        slow, fast = head.next, head.next.next
        while slow!= fast:
            if fast.next is None or fast.next.next is None:
                return None
            
            slow = slow.next
            fast = fast.next.next
        
        fast = head
        while slow != fast:
            slow = slow.next
            fast = fast.next
        
        return slow
        

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81771600