牛客在线习题:链表的k各节点翻转

题目描述

将给出的链表中的节点每 \ k k 个一组翻转,返回翻转后的链表
若是链表中的节点数不是\ k k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点自己。
要求空间复杂度 \ O(1) O(1)
 
例如:
给定的链表是 1\to2\to3\to4\to512345
对于  \ k = 2 k=2, 你应该返回 2\to 1\to 4\to 3\to 521435
对于  \ k = 3 k=3, 你应该返回 3\to2 \to1 \to 4\to 532145

 解答

class ListNode:    def __init__(self, x):        self.val = x        self.next = Noneclass Solution:    def reverseKGroup1(self, head, k):        if k==0 or head==None :            return        if k==1:            return head        nodelist=[head]        newhead=None        while head.next!=None:            head=head.next            nodelist.append(head)        m=int(len(nodelist)/k)        if m==0:            return nodelist[0]        for i in range(m*k):            if i%k==(k-1):                if newhead==None:                    newhead=nodelist[i]                else:                    nodelist[i-2*k+1].next=nodelist[i]            else:                if i%k==0:                    nodelist[i].next=None                nodelist[i+1].next=nodelist[i]        if m * k < len(nodelist):            if nodelist[m * k] != None:                nodelist[m * k - k].next = nodelist[m * k]        return newhead
相关文章
相关标签/搜索