LeetCode-25. K 个一组翻转链表 -- Python解

原题描述

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

示例 1:

LeetCode-25. K 个一组翻转链表 -- Python解_第1张图片

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

示例 2:
LeetCode-25. K 个一组翻转链表 -- Python解_第2张图片

输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]

提示:
链表中的节点数目为 n
1 <= k <= n <= 5000
0 <= Node.val <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        tmp_head = ListNode(-1)
        tmp_head.next = head
        pre = tmp_head
        while head:
            tail = pre
            for i in range(k):
                tail = tail.next
                if not tail:
                    return tmp_head.next

            next_node = tail.next
            head,tail = self.revers(head, tail)
            pre.next = head
            tail.next = next_node
            pre = tail
            head = next_node

        return tmp_head.next

    def revers(self,head:ListNode,tail:ListNode):
        pre = tail.next
        tmp_head = head
        while pre != tail:
            next_node = tmp_head.next
            tmp_head.next = pre
            pre = tmp_head
            tmp_head = next_node
        return tail,head

你可能感兴趣的:(LeetCode,算法,算法,数据结构)