Leetcode 25.K个一组反转链表


要点:
- 返回链表头结点
- 反转后子链表能够与原链表相接
- 反转链表
- 查找剩余是否足够k个
# 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 reverse(self,head,tail): #反转链表
cur=head
prev=tail.next
while prev!=tail:
nex=cur.next
cur.next=prev
prev=cur
cur=nex
return tail,head
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
hair=ListNode(0) #用于最后返回头结点
hair.next=head
pre=hair #记录需反转子链表的前一个结点,方便后续连接
tail=pre
while head:
tail=pre
for i in range(k): #查找是否有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 #在反转链表操作中已将原头结点与nex相连
pre=tail
head=tail.next
return hair.next

浙公网安备 33010602011771号