forked from fuellee/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbers_iter.cpp
64 lines (56 loc) · 1.49 KB
/
AddTwoNumbers_iter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include "ListNode.hpp"
// Definition for singly-linked list.
using namespace std;
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *dumy = new ListNode(0);
ListNode *cur = dumy;
int val=0,c=0;
while(!(l1==nullptr && l2==nullptr)){
if(l1==nullptr){
val = l2->val + c;
c = val/10;
val = val%10;
cur = cur->next = new ListNode(val);
l2 = l2->next;
}
else if(l2==nullptr){
val = l1->val + c;
c = val/10;
val = val%10;
cur = cur->next = new ListNode(val);
l1 = l1->next;
}
else {
val = l1->val + l2->val + c;
c = val/10;
val = val%10;
cur = cur->next = new ListNode(val);
l1 = l1->next;
l2 = l2->next;
}
}
if(c==1)
cur->next=new ListNode(1);
return dumy->next;
}
};
int main() {
#define N new ListNode
Solution s;
ListNode *l1 = N(2,N(4,N(3)));
ListNode *l2 = N(5,N(6,N(4)));
s.addTwoNumbers(l1,l2)->show();
l1 = N(5);
l2 = N(5);
s.addTwoNumbers(l1,l2)->show();
l1 = N(9,N(8));
l2 = N(1);
s.addTwoNumbers(l1,l2)->show();
l1 = N(1,N(8));
l2 = N(0);
s.addTwoNumbers(l1,l2)->show();
return 0;
}