【LeetCode】002 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

题解:

  

 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         ListNode dummy(-1);
13         ListNode* pre = &dummy;
14         int carry = 0;
15         
16         while (l1 || l2) {
17             int addend1 = l1 == nullptr ? 0 : l1->val;
18             int addend2 = l2 == nullptr ? 0 : l2->val;
19             int sum = addend1 + addend2 + carry;
20             ListNode* cur = new ListNode(sum % 10);
21             pre->next = cur;
22             pre = pre->next;
23             carry = sum / 10;
24             
25             if (l1)
26                 l1 = l1->next;
27             if (l2)
28                 l2 = l2->next;
29         }
30         
31         if (carry) {
32             ListNode* cur = new ListNode(carry);
33             pre->next = cur;
34         }
35         return dummy.next;
36     }
37 };
原文地址:https://www.cnblogs.com/Atanisi/p/6713957.html