forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
54 lines (41 loc) · 1.09 KB
/
main2.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
/// Source : https://leetcode.com/problems/add-two-numbers/description/
/// Author : liuyubobobo
/// Time : 2018-08-09
#include <iostream>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Using l1 as the result list
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p1 = l1, *p2 = l2;
ListNode* pre = NULL;
int carried = 0;
while(p1 || p2){
int a = p1 ? p1->val : 0;
int b = p2 ? p2->val : 0;
if(p1)
p1->val = (a + b + carried) % 10;
else{
pre->next = new ListNode((a + b + carried) % 10);
p1 = pre->next;
}
carried = (a + b + carried) / 10;
pre = p1;
p1 = p1->next;
if(p2) p2 = p2->next;
}
pre->next = carried ? new ListNode(1) : NULL;
return l1;
}
};
int main() {
return 0;
}