Adding two number represented by linklist (leetcode, cpp solution)

Adding two number represented by linklist (leetcode, cpp solution)

 

 

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807. 
 
 
----------------------------------------------------------------------------------------------
class Solution {
public:

ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) {


ListNode* temp;
temp=l1;

int carry=0;


while(1)
{
temp->val=((temp->val+l2->val));


if(temp->next!=NULL && l2->next!=NULL)
{
temp=temp->next;
l2=l2->next;
}
else
{
if(temp->next==NULL && l2->next!=NULL)
{
temp->next=l2->next;
break;
}
else
break;

}

}

temp=l1;
ListNode* prev;

while(temp)
{
int x;
x=carry+temp->val;

temp->val=x%10;
carry=x/10;
prev=temp;
temp=temp->next;


}
if(carry>0)
{
ListNode* node=new ListNode();
node->val=carry;
node->next=NULL;
prev->next=node;

}

return l1;

}
};

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).