题意:Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
参考代码(非递归):
def reverseList(self, head):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
参考代码(递归):
def reverseList(self, head):
return self._reverse(head)
def _reverse(self, node, prev=None):
if not node:
return prev
n = node.next
node.next = prev
return self._reverse(n, node)