leetcode 链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
python:732ms, 12.4 Mb
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tmp_head = pre_head = ListNode(0)
pre_head.next = head
while self.judgekNode(tmp_head, k):
i = k
nextk_p = self.NodekNext(tmp_head, k + 1)
while i != 1:
self.NodekNext(tmp_head, i).next = tmp_head.next
tmp_head.next = self.NodekNext(tmp_head, i)
tmp_head = tmp_head.next
i -= 1
tmp_head = tmp_head.next
tmp_head.next = nextk_p
return pre_head.next
def NodekNext(self, node, k):
while k:
node = node.next
k -= 1
return node
def judgekNode(self, node, k):
node = node.next
while k:
if not node: return False
node = node.next
k -= 1
return True
python: 44ms , 12.7 Mb
class Solution(object):
def reverseKGroup(self, head, k):
cnt = 0
check = head
while cnt < k and check != None:
cnt += 1
check = check.next
if cnt < k:
return head
point = head
prev = self.reverseKGroup(check, k)
while point != check:
tmp = point.next
point.next = prev
prev = point
point = tmp
return prev
其他方法看 leetcode 链接 评论区~