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

  

 

posted @ 2022-03-08 15:53  Aria_2000  阅读(26)  评论(0)    收藏  举报