Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 11, 2013 02:53
Show Gist options
  • Save zhoutuo/4752131 to your computer and use it in GitHub Desktop.
Save zhoutuo/4752131 to your computer and use it in GitHub Desktop.
You are given two linked lists representing two non-negative numbers. 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. 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int left = 0;
ListNode root(-1);
ListNode* cur = &root;
while(l1 != NULL or l2 != NULL or left != 0) {
int sum = 0;
sum += (l1 == NULL ? 0 : l1->val);
sum += (l2 == NULL ? 0 : l2->val);
sum += left;
left = 0;
if(sum > 9) {
sum -= 10;
++left;
}
cur->next = new ListNode(sum);
cur = cur->next;
if(l1 != NULL) {
l1 = l1->next;
}
if(l2 != NULL) {
l2 = l2->next;
}
}
return root.next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment