From adb37d1f765267123d531d3c64492dada7ff2e90 Mon Sep 17 00:00:00 2001 From: Jivat Neet Date: Fri, 8 May 2020 18:33:13 +0530 Subject: [PATCH] Adding solution with better Space Complexity --- C++/AddTwoNumbers_new.cpp | 67 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 C++/AddTwoNumbers_new.cpp diff --git a/C++/AddTwoNumbers_new.cpp b/C++/AddTwoNumbers_new.cpp new file mode 100644 index 00000000..9b5bf64d --- /dev/null +++ b/C++/AddTwoNumbers_new.cpp @@ -0,0 +1,67 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + + if(l1==NULL) + return l2; + + if(l2==NULL) + return l1; + + ListNode *temp1= l1,*prev1=temp1; + ListNode *temp2=l2,*prev2=temp2; + + int sum =0, carry=0; + while(temp1!=NULL && temp2!=NULL){ + + sum = temp1->val + temp2->val +carry; + temp1->val = sum%10; + carry=sum/10; + prev1=temp1; + prev2=temp2; + temp1=temp1->next; + temp2=temp2->next; + + + } + + if(temp1!=NULL && temp2==NULL){ + + while(temp1){ + sum = temp1->val+carry; + temp1->val = sum%10; + carry = sum/10; + prev1 = temp1; + temp1=temp1->next; + } + } + + else if(temp2!=NULL && temp1==NULL){ + while(temp2){ + + sum = temp2->val+carry; + temp2->val = sum%10; + carry = sum/10; + prev1->next = temp2; + prev1=temp2; + temp2=temp2->next; + } + } + + if(carry){ + prev1->next = new ListNode(carry); + } + + return l1; + } +}; \ No newline at end of file