反转链表(LeetCode)

题目

给你单链表的头节点,请你反转链表,并返回反转后的链表

解题

python 复制代码
class ListNode:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next


def reverse_linked_list_recursive(head: ListNode) -> ListNode:
    # 空链表或单节点链表
    if not head or not head.next:
        return head

    # 递归反转子链表
    new_head = reverse_linked_list_recursive(head.next)

    # 处理当前节点
    head.next.next = head
    head.next = None

    return new_head


# 辅助函数:创建链表
def create_linked_list(elements):
    if not elements:
        return None
    return ListNode(elements[0], create_linked_list(elements[1:]))


# 辅助函数:打印链表
def print_linked_list(head: ListNode):
    current = head
    while current:
        print(current.value, end=" -> " if current.next else "\n")
        current = current.next


# 测试代码
if __name__ == '__main__':
    # 创建链表: 1 -> 2 -> 3 -> 4 -> 5
    elements = [1, 2, 3, 4, 5]
    head = create_linked_list(elements)

    print("原始链表:")
    print_linked_list(head)

    reversed_head = reverse_linked_list_recursive(head)

    print("反转后的链表:")
    print_linked_list(reversed_head)

原始链表:

1 -> 2 -> 3 -> 4 -> 5

反转后的链表:

5 -> 4 -> 3 -> 2 -> 1

相关推荐
To_OC10 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
zylyehuo10 小时前
Linux 彻底且安全地删除文件
linux
ServBay15 小时前
9 个 Python 第三方库推荐,不用 AI 都好像多出一个团队
后端·python
用户83562907805115 小时前
如何使用 Python 添加和管理 Excel 批注(完整示例)
后端·python
用户83562907805115 小时前
使用 Python 管理 Excel 工作表:创建、复制、删除与重命名
后端·python
刘马想放假1 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
用户805533698031 天前
主线 U-Boot 上 RK3506:和闭源 rkbin 拔河的三个隐性契约
linux·嵌入式
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
用户034095297911 天前
linux fcitx 5 雾凇拼音 设置在中文输入法下仍然输入英文标点
linux