將給出的鏈表中的節點每
\ k k 個一組翻轉,返回翻轉後的鏈表
若是鏈表中的節點數不是\ k k 的倍數,將最後剩下的節點保持原樣
你不能更改節點中的值,只能更改節點自己。
要求空間複雜度 \ O(1) O(1)
例如:
給定的鏈表是
1\to2\to3\to4\to51→2→3→4→5
對於
\ k = 2 k=2, 你應該返回 2\to 1\to 4\to 3\to 52→1→4→3→5
對於
\ k = 3 k=3, 你應該返回 3\to2 \to1 \to 4\to 53→2→1→4→5
解答
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