每k个节点翻转一组的python实现
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
# write code here
dummy = ListNode(0)
dummy.next = head
pre, end = dummy, dummy
while end.next:
for i in range(k):
if end:
end = end.next
if not end: break
#把子表孤立出来
start = pre.next
start_next = end.next
end.next = None
#完成子表的反转
pre.next = self.reverseList(start)
start.next = start_next
pre = start
end = start
return dummy.next
def reverseList(self, head):
pre = None
cur = head
while cur:
cur.next, cur, pre = pre, cur.next, cur
return pre