-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.cpp
More file actions
33 lines (33 loc) · 798 Bytes
/
Copy pathAddTwoNumbers.cpp
File metadata and controls
33 lines (33 loc) · 798 Bytes
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
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
class Solution {
public:
/* Sol 0
* Use a sentinel.
*/
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p=l1,*q=l2,head=ListNode(-1);
ListNode *tail=&head;
int sum = 0;
while(p!=nullptr || q!=nullptr){
sum /= 10;
if(p!=nullptr){
sum += p->val;
p=p->next;
}
if(q!=nullptr){
sum += q->val;
q=q->next;
}
tail->next = new ListNode(sum%10);
tail = tail->next;
}
if(sum/10 == 1) tail->next = new ListNode(1);
return head.next;
}
};