You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
**/Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//case 1: l1 or l2 is empty
if (l1==NULL) return l2;
if (l2==NULL) return l1;
//normal case
ListNode* newHead = NULL;
ListNode* prep = NULL;
ListNode* curr = NULL;
int sum;
int reminder;
bool plus;
newHead = new ListNode(l1->val+l2->val);
if(newHead->val >= 10){
newHead->val = newHead->val - 10;
plus = true;
}
else{
plus = false;
}
prep = newHead;
l1=l1->next;
l2=l2->next;
while((l1!=NULL)&&(l2!=NULL)){
sum = l1->val+l2->val;
if(plus) sum++;
if(sum>=10){
sum = sum - 10;
plus = true;
}
else {
plus = false;
}
curr = new ListNode(sum);
prep->next = curr;
prep = curr;
l1=l1->next;
l2=l2->next;
}
curr = NULL;
if(l1!=NULL){
curr = l1;
}
if(l2!=NULL){
curr = l2;
}
if((l1==NULL)&&(l2==NULL)&&plus){
curr = new ListNode(1);
plus = false;
}
while(curr!=NULL){
if(plus) curr->val++;
if(curr->val >= 10){
curr->val = curr->val-10;
plus = true;
}
else{
plus = false;
}
prep->next = curr;
prep = curr;
curr = curr->next;
}
if(plus){
curr = new ListNode(1);
prep->next = curr;
}
return newHead;
}
};
No comments:
Post a Comment