Add Two Numbers

[題目]

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
出處 leetcode https://leetcode.com/problems/add-two-numbers/description/

兩個數字,分別用link list來表示,請把他們相加後,用link list回傳結果。
位數在list中順序是顛倒的
e.g.
數字342 表示為  2 -> 4 -> 3

[思路]
數字相加的方法就是從低位開始,同位數相加再加上之前的進位,例如十位數相加再加上由個位數來的進位值。加出來的sum%10為本位數的結果,sum/10為進位值。

知道這個原理,那麼就用while loop同時爬兩個list,每個loop round都處理一個位數的相加。每個位數算出來後都建立一個新的node,把node插入result list中。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode d(-1);//dummy head of result list d.next=NULL; ListNode* cur = &d; int carry=0; //main part while(l1 || l2 || carry!=0){ int d1 = l1 ? l1->val : 0; int d2 = l2 ? l2->val : 0; int sum=d1+d2+carry; carry = sum/10; cur->next = new ListNode(sum%10); cur = cur->next; l1 = l1 ? l1->next : NULL; l2 = l2 ? l2->next : NULL; } return d.next; } };