leetcode 25. Reverse Nodes in k-Group的思路与python实现

  • Post author:
  • Post category:python


Given a linked list, reverse the nodes of a linked list

k

at a time and return its modified list.


k

is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of

k

then left-out nodes in the end should remain as it is.

思路

每次循环反转k-1次。反转之前先记住位置,用来反转后连接。

反转之前还要往前走走看,看看数量够不够,不够就不反转就直接return了。

虽然这是hard题,但我觉得只要熟悉了,链表题的难度都差不多。

在代码开头的时候判断k=1的话就直接return head,可以提高很大效率。

我是用循环做的,也可以用递归做。

代码

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head or k == 1:
            return head
        dummy = ListNode(0)
        dummy.next = head
        cur = head
        pre = dummy
        nex = cur.next
        while 1:
            isremain = False
            front = pre
            end = cur
            tempcur = cur
            for i in range(k-1):
                tempcur = tempcur.next
                if not tempcur:
                    return dummy.next
                
            for i in range(k-1):
                pre = cur
                cur = nex
                nex = cur.next
                cur.next = pre
            front.next = cur
            end.next = nex
            
            if not nex:
                break
            
            pre = end
            cur = nex
            nex = cur.next
        return dummy.next



版权声明:本文为qq_35175413原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。