python单链表反转的方法是什么

avatar
作者
猴君
阅读量:0

Python中单链表的反转可以通过迭代或递归实现。

  1. 迭代法:

    def reverseList(head):     prev = None     current = head     while current:         next_node = current.next         current.next = prev         prev = current         current = next_node     return prev 
  2. 递归法:

    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 

以上两种方法都会返回反转后的链表的头节点。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!