[LeetCode] 25.Reverse Nodes in k-Group[UNSOLVED]

  这题很烦 做完满脑子都是箭头。

  这里head之后 和tail之前 不能用next这种形式来给next复制 会造成循环链表 

tailNode.next = headNode.next  # 4 next point to 2
tailprevNode.next = headNode  # 3 next point to 1(when k is large this node many hard to get)

  

  改了之后还是失败的代码:不是1,6 就是死循环

 

    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        # 0 1
        if head == None or head.next == None:
            return head
        # k == 0
        if k == 0 or k == 1:
            return head
        # swap node
        if k > 1:
            #0 node
            dummy = prevNode = ListNode(0)
            dummy.next = head
            #prepare node
            headNode = prevNode.next
            headnextNode = headNode.next
            tailNode = headNode
            tailprevNode = prevNode
            while tailNode != None:    #break when listnode end
                index = 1
                while index < k:            #break when find tailnode in k rule
                    tailNode = tailNode.next
                    tailprevNode = tailprevNode.next
                    index += 1
                #do swap (comment is k =4)
                prevNode.next = tailNode  # 0 next point to 4
                tailprevNode.next = headNode  # 3 next point to 1(when k is large this node many hard to get)
                headNode.next = tailNode.next  # 1 next point to 5
                tailNode.next = headnextNode  # 4 next point to 2



                #prepare for next
                # head = dummy.next
                prevNode = headNode
                tailprevNode = prevNode
                headNode = headNode.next
                if headNode != None:
                    headnextNode = headNode.next
                else:
                    break
                tailNode = headNode
            return head

 

你可能感兴趣的:([LeetCode] 25.Reverse Nodes in k-Group[UNSOLVED])