Easy understand solution. Reverse, add one, reverse back


  • 0
    M
     def plusOne(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            head = self.reverse(head)
            cur = head
            carry = 1
            while cur is not None and carry > 0:
                tmp = carry
                tmp += cur.val
                cur.val = tmp % 10
                carry = tmp / 10
                cur = cur.next
    
            head = self.reverse(head)
            if carry > 0:
                dummy = ListNode(1)
                dummy.next = head
                return dummy
            return head
    
    
        def reverse(self, head):
            if head.next is None:
                return head
            prev = None
            cur = head
            while cur is not None:
                nxt = cur.next
                cur.next = prev
                prev = cur
                cur = nxt
            return prev
    

Log in to reply
 

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