25.Reverse Nodes in k-Group
lc 23 要求分组翻转链表
题干:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
解释:
依旧是非常直白的一个描述,之前我们使用pre,current,next 3个指针完成了链表的翻转,现在要求的是K个翻转
思考:
无论怎么翻转,中间的过程都是一样的使用3个指针从前往后,使用一个count来实现统计个数,最后要把当前段的第一个节点(翻转后的尾节点)指向递归调用这段程序的头节点。
答案:
class Solution(object):
def reverseKGroup(self, head, k):
#count how many nodes
count =0
tmp=head
while tmp!=None:
tmp =tmp.next
count+=1
if count<k:
return head
pre =None
current =head
count=0
while current!=None:
next =current.next
current.next=pre
pre=current
current=next
count+=1
if count ==k:
break
if current ==None:
return pre
else:
head.next =self.reverseKGroup(self,current,k)
return pre
答案补充:
注意一定要计数,最后一段是要保持原状的。