# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
cur = dummy
while head:
p = head
q = p
for i in range(k-1):
q = q.next
head = head.next
if head is None:
return dummy.next
nex = head.next
q.next = None
pre, tail = self.ReverseList(p)
cur.next = pre
tail.next = nex
cur = tail
head = cur.next
return dummy.next
def ReverseList(self, pHead):
# write code here
tail = pHead
pre = None
while pHead:
next = pHead.next
pHead.next = pre
pre = pHead
pHead = next
return pre, tail
官方题解
class Solution:
# 翻转一个子链表,并且返回新的头与尾
def reverse(self, head: ListNode, tail: ListNode):
prev = tail.next
p = head
while prev != tail:
nex = p.next
p.next = prev
prev = p
p = nex
return tail, head
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
hair = ListNode(0)
hair.next = head
pre = hair
while head:
tail = pre
# 查看剩余部分长度是否大于等于 k
for i in range(k):
tail = tail.next
if not tail:
return hair.next
nex = tail.next
head, tail = self.reverse(head, tail)
# 把子链表重新接回原链表
pre.next = head
tail.next = nex
pre = tail
head = tail.next
return hair.next