class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): carry = 0 root = n = ListNode(0) while l1 or l2 or carry: v1 = v2 = 0 if l1: v1 = l1.val l1 = l1.next if l2: v2 = l2.val l2 = l2.next carry, val = divmod(v1+v2+carry, 10) n.next = ListNode(val) n = n.next return root.next
But this consecutive assignments is a little unclear for me, perhaps tuple assignment is better?
I found this Stack Overflow to find out the answer.
n.next = n = ListNode(val) means first n.next = ListNode(val) then n point to the same address
n = n.next = ListNode(val) means first n = ListNode(val) , now the n is ListNode(val), then n.next point to the address ListNode(val) which means point to itself!!!
Hope this will help.
nice solution! However, I think the variable v1, v2 is unnecessary.
def addTwoNumbers(self, l1, l2): carry = 0; res = n = ListNode(0); while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next; if l2: carry += l2.val; l2 = l2.next; carry, val = divmod(carry, 10) n.next = n = ListNode(val); return res.next;
n.next = n = ListNode(val) 与 n = n.next = ListNode(val)
is there any different?thanks
Almost the same idea as my. But I don't make good use of these functions already included in Python. I make it by myself.
may be slow when adding one small number with a large number like 1 plus 100000000, I use the way that appending the rest of link list to the final result when one of the list is None and the carry is 0
@tusizi I didn't go on this site for a long time, yes from CheckiO, you too?
@mxmingya It just checks if the current node is None
@mxmingya l1 = list 1
l2 = list 2
Please can some one tell me what is this ListNode class I don't find it online though
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.