反转链表 II(LeetCode)

题目

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <=right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

解题

class ListNode:
    def __init__(self, value=0, next=None):
        self.value = value
        self.next = next


def reverseBetween(head: ListNode, left: int, right: int) -> ListNode:
    if left == 1:
        # 从头开始反转前 right 个节点
        return reverseN(head, right)
    # head 的 next 不变,但 next 部分从 left - 1 开始反转到 right - 1
    head.next = reverseBetween(head.next, left - 1, right - 1)
    return head


# 辅助变量,记录第 n+1 个节点,以便在反转完成后重新连接链表。
successor = None


def reverseN(head: ListNode, n: int) -> ListNode:
    """反转以 head 为起点的 n 个节点,返回新的头结点"""
    if n == 1:
        # 记录第 n+1 个节点
        global successor
        successor = head.next
        return head
    # 递归反转前 n-1 个节点
    last = reverseN(head.next, n - 1)
    head.next.next = head
    # 让反转之后的 head 节点和后面的节点连起来
    head.next = successor
    return last


# 创建链表的辅助函数
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__':
    # 使用 create_linked_list 函数创建链表
    elements = [1, 2, 3, 4, 5]
    head = create_linked_list(elements)

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

    # 反转从位置 2 到位置 4 的链表部分
    left, right = 2, 4
    new_head = reverseBetween(head, left, right)

    # 打印反转后的链表
    print("反转一部分后的链表:")
    print_linked_list(new_head)

原始的链表:
1 -> 2 -> 3 -> 4 -> 5
反转一部分后的链表:
1 -> 4 -> 3 -> 2 -> 5

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值