要将单链表逆序,可以使用迭代或递归的方式来实现。

  1. 迭代法:
    • 定义三个指针:prev、current 和 next,分别指向前一个节点、当前节点和后一个节点。
    • 遍历链表,将当前节点的 next 指针指向前一个节点。
    • 更新 prev、current 和 next 指针,继续遍历链表。
    • 当 next 指针为空时,表示遍历到了链表的最后一个节点,将最后一个节点作为新链表的头节点。
    • 返回新链表的头节点。

以下是使用迭代法逆序单链表的示例代码:

def reverseLinkedList(head):
    prev = None
    current = head
    while current:
        next = current.next
        current.next = prev
        prev = current
        current = next
    return prev
  1. 递归法:
    • 递归法的思路是先逆序后面的节点,再将当前节点的 next 指针指向前一个节点。
    • 递归终止条件是当前节点或下一个节点为空。
    • 递归函数返回新链表的头节点。

以下是使用递归法逆序单链表的示例代码:

def reverseLinkedList(head):
    if not head or not head.next:
        return head
    new_head = reverseLinkedList(head.next)
    head.next.next = head
    head.next = None
    return new_head

这两种方法都可以实现单链表的逆序,具体使用哪种方法取决于个人的喜好和需求。


原文地址: https://www.cveoy.top/t/topic/6Rn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录