25. Reverse Nodes in k-Group

def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if not head or k == 1:
            return head
        
        res = head
        for i in range(k-1):
            if not res:
                return head
            res = res.next
        
        Dummy = ListNode(-1)
        Dummy.next = head
        
        pre = Dummy
        cur = head
        while True:
            last = cur
            # 先获取last,last最后会走出当前的k个ListNode,最后一次判断last是在第k个Node的时候。
            for i in range(k):
                if not last:
                    return Dummy.next
                last = last.next
            
            temp = None
            end = cur
            for i in range(k):
                nextN = cur.next
                cur.next = temp
                
                temp = cur
                cur = nextN
                
            end.next = last
            pre.next = temp
            
            #注意pre设置为end,就是反转前的第一个ListNode
            pre = end
            cur = last

你可能感兴趣的:(25. Reverse Nodes in k-Group)