ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
while (l1  l2  extra) {
int sum = (l1 ? l1>val : 0) + (l2 ? l2>val : 0) + extra;
extra = sum / 10;
p>next = new ListNode(sum % 10);
p = p>next;
l1 = l1 ? l1>next : l1;
l2 = l2 ? l2>next : l2;
}
return preHead.next;
}
[c++] Sharing my 11line c++ solution, can someone make it even more concise?


How about this?
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode preHead(0), *p = &preHead; int extra = 0; while (l1  l2  extra) { if (l1) extra += l1>val, l1 = l1>next; if (l2) extra += l2>val, l2 = l2>next; p>next = new ListNode(extra % 10); extra /= 10; p = p>next; } return preHead.next; }

C does not have class or C++ struct, so you can only use C struct, and it has no constructor nor methods. So ListNode will look like
struct ListNode { int val; struct ListNode *next; };
and we would create a function to create and initialize a ListNode
struct ListNode *list_node_new(int x) { struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode)); node>next = NULL; node>val = x; }
then we can
p>next = list_node_new(sum % 10);




I think this is about as concise as you can get. Use the sentinel val field for the sum and carry; condense an assignment into the while condition and another assignment into the current node assignment.
/** * Concise solution. Uses sentinel val field as sum and carry. * * NOTE: (sentinal /= 10) needs to be the first operand of while condition. * Otherwise, boolean expression can shortcircuit when l1 or l2 * are not null, causing sentinel.val to not be decreased for the * next iteration. */ ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode sentinel(0), *c = &sentinel; while((sentinel.val /= 10)  l1  l2) { if(l1) sentinel.val += l1>val, l1 = l1>next; if(l2) sentinel.val += l2>val, l2 = l2>next; c = (c>next = new ListNode(sentinel.val % 10)); } return sentinel.next; }

@BatCoder
preHead
is a dummy node with a next field that points to the head of the list. Once we are done constructing the linked list containing the desired sum, we wish to return the head of the linked list that we just constructed. We can't access the head of the linked list via the pointerp
since we usedp
to construct the new linked list, hencep
no longer points to thepreHead
node nor is it likely thatp
points to the head of the list. However, we still have the unalteredpreHead
node whose next field points to the head of the list! Therefore, we can simply return the head of the linked list viapreHead.next


@tanmays ListNode has a constructor ListNode(int x) and in c++ it is new which dynamically allocates
struct ListNode {

int val;

ListNode *next;

ListNode(int x) : val(x), next(NULL) {}

