https://leetcode.com/problems/add-two-numbers/
1. Build a new List:
//32 ms 70.3 MB/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/class Solution {public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* dummy = new ListNode(-1);ListNode* curr = dummy;int carry = 0;while(l1 || l2){int a = l1 ? l1->val : 0;int b = l2 ? l2->val : 0;curr->next = new ListNode((a + b + carry) % 10);carry = (a + b + carry) / 10;l1 = l1 ? l1->next : NULL;l2 = l2 ? l2->next : NULL;curr = curr->next;}if(carry!=0)curr->next = new ListNode(1);return dummy->next;}};
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclass Solution(object):def addTwoNumbers(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""dummy = curr = ListNode(-1)carry = 0while l1 or l2 or carry:v1 = v2 = 0if l1:v1 = l1.vall1 = l1.nextif l2:v2 = l2.vall2 = l2.nextnval = v1 + v2 + carryif nval >= 10:carry = 1else:carry = 0curr.next = ListNode(nval % 10)curr = curr.nextreturn dummy.next
/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {dummy := &ListNode{}curr := dummycarry := 0for ;(l1 != nil || l2 != nil || carry > 0); curr = curr.Next{if l1 != nil{carry += l1.Vall1 = l1.Next}if l2 != nil{carry += l2.Vall2 = l2.Next}curr.Next = &ListNode{carry % 10, nil}/*if carry >= 10 {carry = 1} else {carry = 0}*/carry /= 10}return dummy.Next}
