Recursion // Double reverse Python solution


  • 0
    K
    def plusOne(head):
        return reverse(head)
    
    def reverse(head):
        if head == None:
            return None
        carry = reverse(head.next)
        if carry == 0:
            return 0
        carry,val = divmod(head.val+1, 10)
        head.val = val
        return carry
    
    ###############################################
    def plusOne(head):
        rev_head = reverse(head)
        link = rev_head
        v = 1
    
        while rev_head or v:
            v,val = divmod(v+rev_head.val, 10)
            rev_head.val = val
            rev_head = rev_head.next
        return reverse(link)
    
    def reverse(head):
        pre = None
        cur = head
        while cur:
            next = cur.next
            cur.next, pre = pre, cur
            cur = next
        cur = pre
        return cur

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.