Python中单链表的反转可以通过迭代或递归实现。
迭代法:
def reverseList(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
递归法:
def reverseList(head):
if not head or not head.next:
return head
new_head = reverseList(head.next)
head.next.next = head
head.next = None
return new_head
以上两种方法都会返回反转后的链表的头节点。