题目

解题

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


def reverseKGroup(head, k):
    """
    翻转链表中每 k 个节点一组的节点。

    :param head: 链表的头节点
    :param k: 每组翻转的节点数量
    :return: 翻转后的链表头节点
    """

    def getKthNode(current, k):
        """
        获取链表中第 k 个节点。

        :param current: 当前节点
        :param k: 节点数量
        :return: 第 k 个节点或 None(如果不足 k 个节点)
        """
        while current and k > 1:
            current = current.next
            k -= 1
        return current

    def reverseLinkedList(head, k):
        """
        翻转链表的一部分。

        :param head: 部分链表的头节点
        :param k: 节点数量
        :return: 翻转后的链表头节点
        """
        previous, current = None, head
        while k:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
            k -= 1
        return previous

    # 找到第 k 个节点
    kth_node = getKthNode(head, k)
    if not kth_node:
        return head

    next_group_head = kth_node.next
    kth_node.next = None

    # 翻转当前 k 个节点
    new_head = reverseLinkedList(head, k)

    # 递归处理剩余链表,并连接
    head.next = reverseKGroup(next_group_head, k)

    return new_head


def listToListNode(arr):
    """
    将 Python 列表转换为链表。

    :param arr: Python 列表
    :return: 链表的头节点
    """
    dummy = ListNode()
    current = dummy
    for val in arr:
        current.next = ListNode(val)
        current = current.next
    return dummy.next


def listNodeToList(head):
    """
    将链表转换为 Python 列表。

    :param head: 链表的头节点
    :return: Python 列表
    """
    result = []
    while head:
        result.append(head.val)
        head = head.next
    return result


def testReverseKGroup():
    """
    测试 reverseKGroup 函数。
    """
    test_cases = [
        ([1, 2, 3, 4, 5], 2),
        ([1, 2, 3, 4, 5], 3),
        ([1, 2, 3, 4, 5], 1),
        ([1], 1),
        ([1, 2], 2)
    ]

    for i, (input_list, k) in enumerate(test_cases):
        head = listToListNode(input_list)
        new_head = reverseKGroup(head, k)
        output_list = listNodeToList(new_head)
        print(output_list)


# 运行测试代码
testReverseKGroup()
08-06 16:19