Skip to content

Instantly share code, notes, and snippets.

@zhanglaplace
Created September 5, 2017 08:17
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 zhanglaplace/d020da5e0fc4334d669ff7a224ed24be to your computer and use it in GitHub Desktop.
Save zhanglaplace/d020da5e0fc4334d669ff7a224ed24be to your computer and use it in GitHub Desktop.
4offer
/*******************************************************************
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
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) {
if(l1==nullptr && l2==nullptr)
return nullptr;
ListNode* head = new ListNode(0);
ListNode* ptr = head;
ptr->next = nullptr;
int carry = 0;
while(l1 != nullptr || l2 != nullptr){
int sum = 0;
sum += carry;
if(l1 != nullptr){
sum += l1->val;
l1 = l1->next;
}
if(l2!= nullptr){
sum += l2->val;
l2 = l2->next;
}
ListNode* temp = new ListNode(sum%10);
carry = sum/10;
ptr->next = temp;
ptr = ptr->next;
}
if(carry == 1){
ListNode* temp = new ListNode(1);
ptr->next = temp;
ptr = ptr->next;
}
ptr->next = nullptr;
return head->next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment