2. 两数相加

 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        //定义一个新链表res,一个temp的链表cur,用来当作res的指针,一个进位标志carry
13         ListNode *res = new ListNode(-1);
14         ListNode *cur = res;
15         int carry = 0;
16         while(l1 != NULL || l2 != NULL){
17             //取到两个链表当前的数值
18             int num1 = l1 == NULL ? 0 : l1->val;
19             int num2 = l2 == NULL ? 0 : l2->val;
20             //求和
21             int sum = num1 + num2 + carry;
22             //对进位标志的验证
23             carry = sum >= 10 ? 1 : 0;
24             cur->next = new ListNode(sum % 10);
25             cur = cur->next;
26             l1 = l1 ? l1->next : l1;
27             l2 = l2 ? l2->next : l2;
28         }
29         if (carry == 1) {
30             cur->next = new ListNode(1);
31         }
32         return res->next;   
33     }
34 };
原文地址:https://www.cnblogs.com/ouyang_wsgwz/p/8830120.html