本题是一个hard链表翻转问题,关键点如下:
1.子链表翻转,需要有一个头节点指引返回结果的head
2.题目有空间要求,合适的做法是先计数再做子链表翻转
代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseSubList(self, currN, groupL):
preN = None
while groupL:
nextN = currN.next
currN.next = preN
preN = currN
currN = nextN
groupL -= 1
return preN
def reverseKGroup(self, head, k):
end = head
dummy = ListNode(0) #head之前的节点
result = dummy
length = 1
while end:
end = end.next
if length != k:
length += 1
else:
dummy.next = self.reverseSubList(head, k) #返回已经倒序的子链的head,被前一个节点指引
dummy = head #head是本子链第一个节点,倒叙后为下个子链的head前一个节点,传给dumy
head = end #end为下个子链第一个节点,给head
length = 1
dummy.next = head #若后面的子链长度小于k,则直接传给dummy,否则此处传的是None
return result.next