原题链接:https://leetcode.com/problems/reverse-nodes-in-k-group/
解题思路:这道题是reverse two的升级版,我的代码其实效率很低。首先用了两个标记,一个start指向当前正在reverse的group的第一个,另一个next_start指向下一组的第一个。然后要next_n标记pre要指向的,用cur标记next_n要指向的。一组一组进行,每一次纳入一个新的节点;完成一组后判断下一组是否够三个,够的话再继续reverse。
【leetcode刷题】25. Reverse Nodes in k-Group代码:

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        # initializetion
        pre = ListNode(0)
        pre.next = head
        cur_node = head
        head = pre
        next_start = cur_node

        while cur_node:
            count = 0
            while count < k and next_start:
                next_start, count = self.countSubList(next_start, count)
            if count < k:
                return head.next

            start = pre.next
            next_node = cur_node.next
            while next_node != next_start:
                cur_node, next_node = self.reverseOne(pre, cur_node, next_start, next_node)

            pre = start
            cur_node = pre.next
        return head.next

    def reverseOne(self, pre, cur, next_start, next_node):
        pre.next = next_node
        next_node = next_node.next
        pre.next.next = cur
        # cur node move 1 forward in the previous order
        if cur.next==pre.next:
            cur.next = next_start
        cur = pre.next
        return cur, next_node

    def countSubList(self, next_start, count):
        next_start = next_start.next
        count += 1
        return next_start, count

相关文章:

  • 2021-10-06
  • 2021-10-03
  • 2021-11-29
  • 2021-11-14
  • 2022-12-23
  • 2021-10-20
  • 2021-10-29
  • 2021-10-11
猜你喜欢
  • 2021-07-26
  • 2021-04-30
  • 2022-01-15
  • 2021-05-18
  • 2021-11-17
  • 2022-02-17
相关资源
相似解决方案