方法一:递归反转链表
递归过程理解图示见:leetcode 206. 反转链表(python) - 知乎 (zhihu.com)
空间复杂度O(n)
def trainningPlan(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
#递归反转
# 如果链表为空或只有一个节点,直接返回该节点
if head is None or head.next is None:
return head
# 递归
temp = self.trainningPlan(head.next)
head.next.next = head
head.next = None
return temp
方法二:迭代反转链表
表现为原地反转
def trainningPlan(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
#原地反转--一个while循环实现,
#通过迭代的方式逐步改变每个节点的next指针,直到整个链表被反转
pre = None
current = head
while current is not None:
next_node = current.next
current.next = pre
pre = current
current = next_node
return pre
拓宽:什么时候需判断链表为空或只有一个节点
java进行迭代时,需要首先判断链表为空或只有一个节点,而在上述的python的迭代过程中已包含为空或只有一个节点的情况。
另外,在Java中,通常会在递归函数中加入这样的检查来防止栈溢出错误,因为Java的默认栈大小有限,而Python解释器通常会有更大的默认栈大小,因此在Python中通常不需要这样的检查。