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
以上兩種方法都會返回反轉后的鏈表的頭節點。