新方法!!!!-20%-错在那里-python3?

链表中环的入口节点

http://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad

错误描述

图片说明

方法解释:

遍历所有节点,将遍历过的节点的next设置为特殊节点X,
终止条件:如果遍历到某节点的next==X,则说明此节点遍历过了,但是又遍历到它了,ok,return
否则,直接return None

代码:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def detectCycle(self , head ):
        if head==None: return None # 如果空链表,
        tmp = head
        if tmp.next==tmp: return tmp #如果自己指向自己
        nodes = ListNode('@')
        while(tmp != None):
            if (tmp.next == nodes)or(tmp.next==tmp):#如果指向特殊节点,或自身
                return tmp
            tmp2 = tmp.next
            tmp.next = nodes
            tmp = tmp2
        return None
        # write code here
全部评论
最后返回的节点被破坏了,等于变了
点赞
送花
回复 分享
发布于 2020-11-18 22:08

相关推荐

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