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

4622 단어
이 문제는 귀찮아서 다 풀면 온통 화살촉이다.
여기 헤드 이후와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

좋은 웹페이지 즐겨찾기