classListNode:def__init__(self, x):
self.val = x
self.next=Nonedef__str__(self):return'val:%d'% self.val
classSolution:defreverseKGroup(self, head, k):
dummy = ListNode(0)
dummy.next= head
pre, tail = dummy, dummy
while tail.next:
count = k
while count and tail:
tail, count = tail.next, count-1ifnot tail:break#(pre->start,tail->next)
start = pre.nextnext= tail.next
tail.next=None#翻转k个节点,即[start,tail]并连接好
pre.next= self.reverseList(start)#[tail,start]--->next
start.next=next#归位,为下一次翻转做准备
pre = start
tail = pre
return dummy.nextdefreverseList(self, head: ListNode)-> ListNode:
cur, pre = head,Nonewhile cur:
cur.next, pre, cur = pre, cur, cur.nextreturn pre
if __name__ =='__main__':
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
f = ListNode(6)#构造一个简单链表
a.next, b.next, c.next, d.next, e.next= b, c, d, e, f
p = a
while(p):print(p.val)
p=p.nextprint("----------------")
p=Solution().reverseKGroup(a,5)while(p):print(p.val)
p = p.next