嗨,這是一個鏈接列表反向代碼。任何人都可以幫助我理解r = Solution()。reverseList(n1)和r = Solution()。reverseList(ListNode(1))之間的差異。鏈接列表反向代碼中的對象變量
我想知道爲什麼分別是[1]和[3,2,1]的輸出以及將ListNode對象分配給變量的目的是什麼。
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#if not head:
# return None
prev = head
curr = prev.next
while curr:
next =curr.next
curr.next = prev
prev = curr
curr = next
head.next = None
return prev
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
def to_list(self):
return[self.val] + self.next.to_list() if self.next else [self.val]
if __name__ == "__main__":
n1 = ListNode(1)
n2 = ListNode(2)
n3 = ListNode(3)
n1.next = n2
n2.next = n3
r = Solution().reverseList(n1)
print r.to_list()
#assert r.to_list() == [3,2,1]