简体   繁体   English

Python:无法识别局部变量

[英]Python: local variable not recognized

I'm new to python and I'm trying to implement a function that reverses a link list.我是 python 新手,我正在尝试实现一个反转链接列表的函数。

I'm getting the error msg: local variable "new_head" referenced before assignment我收到错误消息:分配前引用了局部变量“new_head”

def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head == None or head.next == None:
            return head
        
        new_head = None
        
        def recur(curr_head):
            if curr_head == None:
                return
            
            next_node = curr_head.next
            curr_head.next = new_head
            new_head = curr_head
            recur(next_node)
            
        recur(head)
        return new_head

The following implementation works but is very ugly, is there an alternative to this?以下实现有效,但非常难看,是否有替代方法?

def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head == None or head.next == None:
            return head
        
        
        new_head = None
        arr = [new_head]
        
        def recur(curr_head):
            if curr_head == None:
                return
            
            temp = curr_head.next
            curr_head.next = arr[0]
            arr[0] = curr_head
            recur(temp)
            
        recur(head)
        return arr[0]

At the beginning of the function recur , you can put:在函数recur的开头,您可以输入:

nonlocal new_head

This allows the inner function recur to modify a variable declared in the outer function's scope.这允许内部函数recur修改在外部函数作用域中声明的变量。

(It's like the way you need to use global to allow a function to modify a module-scope variable.) (这就像您需要使用global来允许函数修改模块范围变量的方式。)

Python documentation Python 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM