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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容