原题链接:https://leetcode.com/problems/reverse-nodes-in-k-group/
解题思路:这道题是reverse two的升级版,我的代码其实效率很低。首先用了两个标记,一个start指向当前正在reverse的group的第一个,另一个next_start指向下一组的第一个。然后要next_n标记pre要指向的,用cur标记next_n要指向的。一组一组进行,每一次纳入一个新的节点;完成一组后判断下一组是否够三个,够的话再继续reverse。
代码:
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# initializetion
pre = ListNode(0)
pre.next = head
cur_node = head
head = pre
next_start = cur_node
while cur_node:
count = 0
while count < k and next_start:
next_start, count = self.countSubList(next_start, count)
if count < k:
return head.next
start = pre.next
next_node = cur_node.next
while next_node != next_start:
cur_node, next_node = self.reverseOne(pre, cur_node, next_start, next_node)
pre = start
cur_node = pre.next
return head.next
def reverseOne(self, pre, cur, next_start, next_node):
pre.next = next_node
next_node = next_node.next
pre.next.next = cur
# cur node move 1 forward in the previous order
if cur.next==pre.next:
cur.next = next_start
cur = pre.next
return cur, next_node
def countSubList(self, next_start, count):
next_start = next_start.next
count += 1
return next_start, count