LeetCode 142的解法,求求帮看哪里错了

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

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if not head:
            return None
        slow,fast = head,head
        mixed= None
        while fast and fast != slow:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                slow = head
                while fast != slow:
                    fast = fast.next
                    slow = slow.next
                mixed = slow
                break

        if not mixed:
            return None
        else:
            i = 0
            while head!=mixed:
                head = head.next
                i+=1
            return i



我的思路是这样的: 用两个slow和fast指针,slow指针每次移动一步,fast每次移动两步,如果有环,fast和slow相遇,然后slow从头节点,fast从相遇位置,每次移动一步,相交点就是入环节点,然后算出相交节点的位置i;如果无环,mixed==None,结果也return None。
结果没有通过,这种链表到pycharm也不太好打断点,求问哪里错了?





#leetcode#
全部评论
为什么一定在入环节点相交?
点赞 回复
分享
发布于 2019-11-14 03:06
你这while 就有问题
点赞 回复
分享
发布于 2019-11-14 03:11
联易融
校招火热招聘中
官网直投
# Definition for singly-linked list. # class ListNode: #     def __init__(self, x): #         self.val = x #         self.next = None class Solution:     def detectCycle(self, head: ListNode) -> ListNode:         if not head:             return None         slow,fast = head,head         mixed= None         while fast.next and fast.next.next:             fast = fast.next.next             slow = slow.next             if fast == slow:                 slow = head                 while fast != slow:                     fast = fast.next                     slow = slow.next                 return slow         return None 封贴,这题目的输出也 不说清楚,我以为要返回相交节点的位置呢😥
点赞 回复
分享
发布于 2019-11-14 03:59

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务