File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < iostream>
2+ using namespace std ;
3+
4+ struct ListNode {
5+ int val;
6+ ListNode *next;
7+ ListNode (int x) : val(x), next(NULL ) {}
8+ };
9+
10+ class Solution {
11+ public:
12+ ListNode *addTwoNumbers (ListNode *l1, ListNode *l2) {
13+ int add = 0 ;
14+ ListNode *ret (NULL ), *cur (NULL );
15+ while (true ) {
16+ int s = add;
17+ if (ret == NULL ) {
18+ s += l1->val + l2->val ;
19+ } else {
20+ if (l1 != NULL ) s += l1->val ;
21+ if (l2 != NULL ) s += l2->val ;
22+ }
23+ ListNode *t = new ListNode (s % 10 );
24+ add = s / 10 ;
25+
26+ if (ret == NULL ) ret = t;
27+ else cur->next = t;
28+ cur = t;
29+
30+ if (l1 != NULL ) l1 = l1->next ;
31+ if (l2 != NULL ) l2 = l2->next ;
32+ if (l1 == NULL && l2 == NULL ) break ;
33+ }
34+ if (add == 1 ) {
35+ ListNode *t = new ListNode (1 );
36+ cur->next = t;
37+ }
38+ return ret;
39+ }
40+ };
You can’t perform that action at this time.
0 commit comments