在递归的行(l1 = sortList(head)
)中,我得到NameError: global name 'sortList' is not defined
。
谁能指出我做错了什么?
class Solution:
# @param head, a ListNode
# @return a ListNode
def sortList(self, head):
if head == None or head.next == None:
return head
slow = head
fast = head
while fast != None and fast.next != None:
slow = slow.next
fast = fast.next.next
fast = slow
slow = slow.next
fast.next = None
l1 = sortList(head)
l2 = sortList(slow)
l = mergeTwoLists(l1, l2)
return l
答案 0 :(得分:3)
sortList
是Solution
的方法,并不是独立存在的。
使用:
self.sortList(head)
它会起作用。
答案 1 :(得分:0)
将l1 = sortList(head)
更改为l1 = self.sortList(head)
,将l2 = sortList(slow)
更改为l2 = self.sortList(slow)
。 sortList
在Solution
类中定义,并且不存在全局,这就是您需要self
引用当前Solution
对象的原因。
答案 2 :(得分:0)
您尚未导入任何名为sortList
的函数,因此只能在sortList
对象上调用Solution
。
使用self.sortList
。 self
是python中用于引用当前对象的变量。与其他语言中的this
非常相似。