python

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

小亿
52
2023-12-06 19:42:53
栏目: 编程语言

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
    

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

0
看了该问题的人还看了