I'm new to python and I'm trying to implement a function that reverses a link list.
I'm getting the error msg: local variable "new_head" referenced before assignment
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:
nonlocal new_head
This allows the inner function recur
to modify a variable declared in the outer function's scope.
(It's like the way you need to use global
to allow a function to modify a module-scope variable.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.