LeetCode --- Add Two Numbers

题目链接

说来算是个基础题目,可是还是各种CE,各种WA,基础还是不扎实。

附上代码:

 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 == NULL) return l2;
13         if (l2 == NULL) return l1;
14         // q: keep trace of the linked list that has been produced as the answer
15         // ll1: keep trace of l1
16         // ll2: keep trace of l2
17         ListNode *head(NULL), *q(NULL), *ll1 = l1, *ll2 = l2;
18         // c: holds the carry digit 
19         int c = 0;
20         while (ll1!=NULL || ll2!=NULL) {
21             // sum: holds sum of ll1->val, ll2->val and c
22             int sum = 0;
23             if (ll1 != NULL) {
24                 sum += ll1->val;
25                 ll1 = ll1->next;
26             }
27             if (ll2 != NULL) {
28                 sum += ll2->val;
29                 ll2 = ll2->next;
30             }
31             sum += c;
32             ListNode *p = new ListNode(sum%10);
33             c = sum >= 10 ? 1 : 0;
34             if (head == NULL) {
35                 head = q = p;
36             } else {
37                 q->next = p;
38                 q = p;
39             }
40         }
41         if (c) {
42             q->next = new ListNode(c);
43         }
44         return head;
45     }
46 };
原文地址:https://www.cnblogs.com/Stomach-ache/p/3754409.html