我正在通过递归方法尝试Python中的反向链接列表程序。
这是我写的代码:
class Solution:
def reverseList(self, head: ListNode):
if( head == None or head.next == None):
return head
newHead = Solution().reverseList(head.next)
head.next.next = head
head = None
return newHead
我分别定义了
ListNode
如下:
class ListNode:
def __init__(self, val =0, next= None):
self.val= val
self.next= next
当我在Python中尝试递归时,我不明白如何使用
self
。上面的代码不能按原样工作。
我尝试将
self
放入上面的方法中的不同位置,但不明白到底要做什么才能使此代码工作。
有时它会进入无限循环,有时它说
reverseList
未定义。
如何更正我的代码?
看起来您使用递归方法来反转链表的方向是正确的。这是代码的更正版本:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead
使用是检查 None 而不是 == 以便更好地与 None 进行比较。反转下一个节点后,将 head.next 设置为 None,以避免链表中形成循环。