可以借鉴以前的反转链表的代码,然后分别一组一组的反转。
属于细节题目,适合反复训练
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head, tail):
if not head:
return head
# 注意这里需要保留与tail之后数据的连接
pre = tail.next
p = head
while pre != tail:
q = p.next
p.next = pre
pre = p
p = q
return pre, head
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode()
dummy.next = head
left = dummy
tail = dummy
# print('left,right,head',left.val, right.val,head.val)
while head:
for i in range(k):
tail = tail.next
if not tail:
return dummy.next
# print('head,tail',head,tail)
# 开始翻转前先记录被翻转部分的左右两部分
right = tail.next
new_head, new_tail = self.reverseList(head, tail)
# print('new_head,new_tail',new_head,new_tail)
# 翻转后的新链表连接到原链表中间
left.next = new_head
new_tail.next = right
# 重新初始化待翻转链表的head、tail以及左半部分
head = new_tail.next
tail = new_tail
left = new_tail
return dummy.next