标签:
Same with add binary. You can also skip delete the result pointer. But just return result->next. Depends on the interviewer.
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 if (!l1) return l2; 13 if (!l2) return l1; 14 ListNode *result = new ListNode(0); 15 ListNode *runner = result; 16 int carry = 0, sum = 0; 17 while (l1 || l2) { 18 sum = carry; 19 if (l1) { 20 sum += l1->val; 21 l1 = l1->next; 22 } 23 if (l2) { 24 sum += l2->val; 25 l2 = l2->next; 26 } 27 carry = sum/10; 28 runner->next = new ListNode(sum%10); 29 runner = runner->next; 30 } 31 if (carry) { 32 runner->next = new ListNode(carry); 33 } 34 runner = result->next; 35 delete result; 36 return runner; 37 } 38 };
LeetCode – Refresh – Add Two Numbers
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4346157.html