Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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) {
- ListNode* temp = new ListNode();
- ListNode* curr = temp;
- int carry=0;
- while(l1!= NULL || l2!=NULL || carry!=0)
- {
- int x,y;
- if(l1)
- {
- x=l1->val;
- }
- else
- {
- x=0;
- }
- if(l2)
- {
- y=l2->val;
- }
- else
- {
- y=0;
- }
- int ans=x+y+carry;
- carry=ans/10;
- curr->next=new ListNode(ans%10);
- curr=curr->next;
- l1=l1?l1->next:nullptr;
- l2=l2?l2->next:nullptr;
- }
- return temp->next;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment