Skip to content

Instantly share code, notes, and snippets.

@himanshu-dixit
Created February 2, 2019 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save himanshu-dixit/25b8af940722db628a1405c6a1ddc98a to your computer and use it in GitHub Desktop.
Save himanshu-dixit/25b8af940722db628a1405c6a1ddc98a to your computer and use it in GitHub Desktop.
add_two_number_leetcode.cpp
/**
* 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) {
int carry = 0;
ListNode* current = new ListNode(0);
ListNode* start = current;
// Loop
while(l1 || l2){
int x1 = l1?l1->val:0;
int x2 = l2?l2->val:0;
int sum = carry + x1 + x2;
carry = sum/10;
current->next = new ListNode(sum%10);
current = current->next;
// Special condition when same no. of element and carry
if(l1){
l1 = l1->next;
}
if(l2){
l2 = l2->next;
}
}
if(carry>0){
current->next = new ListNode(carry);
current = current->next;
}
current->next = NULL;
return start->next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment