共计 337 个字符,预计需要花费 1 分钟才能阅读完成。
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
以上两种方法都会返回反转后的链表的头节点。
丸趣 TV 网 – 提供最优质的资源集合!
正文完