Only one loop cycle with python

class Solution:
# @param A : head node of linked list
# @param B : head node of linked list
# @return the head node in the linked list
def addTwoNumbers(self, num1, num2):

    carrige = 0
    head = ListNode(-1)
    head2 = head
    while num1 or num2:

        if num1 and num2:
            r = num1.val + num2.val + carrige
            val = r % 10
            carrige = r // 10
            head.next = ListNode(val)
            head = head.next
            num1 = num1.next
            num2 = num2.next
        else:
            if num1:
                r = (num1.val + carrige) 
                carrige = r // 10
                head.next = ListNode(r % 10)
                head = head.next
                num1 = num1.next

            if num2:
                r = (num2.val + carrige)
                carrige = r // 10
                head.next = ListNode(r % 10)
                head = head.next
                num2 = num2.next

    if carrige > 0:
        head.next = ListNode(1)

    return head2.next
Click here to start solving coding interview questions