# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next:
return head
if k==1:
return head
dummy=ListNode(0)
dummy.next=head
record=dummy
left=head
right=head.next
count=1
while True:
while right and count<k: #reverse links within a group
tmp=right.next
right.next=left
prev=left
left=right
right=tmp
count+=1
if count==k:#rotate the group#####difficult
count=1
tmp=dummy.next #这个group的第一个
dummy.next=left #这个group里面倒序之后的第一个,group原来的最后一个
tmp.next=right # 原来group的第一个连接下一个group的第一个
dummy=tmp
left=right #准备下一个group的循环
if right:
right=right.next
else:#最后剩下不足k个
if count>=2:
left.next=None
if count>2:#需要将最后一个节点个数不足k的group顺序复原
while True:
tmp=prev.next
prev.next=left
if tmp.next==prev:
return record.next
left=prev
prev=tmp
return record.next
25. Reverse Nodes in k-Group ListNode 链表各个节点顺序倒过来,再复原顺序
猜你喜欢
转载自blog.csdn.net/weixin_45405128/article/details/104696059
今日推荐
周排行