class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
def reverseList(l1): # 翻转列表
if not l1:
return l1
cur = None
while l1.next:
tmp = l1.next
l1.next = cur
cur = l1
l1 = tmp
l1.next = cur
return l1
ahead = ListNode(0)
acur = ahead
while head:
thead = head
count = 1
while head.next and count < k: # 按长度k分段
head = head.next
count += 1
if count == k: # 若长度为k则将该段翻转
tthead = head.next
head.next = None
acur.next = reverseList(thead)
while acur.next:
acur = acur.next
head = tthead
else: # 按长度不足k,则保留顺序放在末尾
acur.next = thead
head = None # 设置结束条件
return ahead.next
[LeetCode Python3] 25. Reverse Nodes in k-Group
最新推荐文章于 2022-04-16 13:37:21 发布