Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 28, 2012 21:18
Show Gist options
  • Select an option

  • Save pdu/4401996 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4401996 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. http://www.leetcode.com/onlinejudge
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// pay attention to pointer and pointer to pointer
void update(ListNode** ret, ListNode** cur, int val) {
ListNode* tmp = new ListNode(val);
if (*ret == NULL) {
*ret = tmp;
}
else {
(*cur)->next = tmp;
}
*cur = tmp;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode* ret = NULL;
ListNode* cur = NULL;
int addon = 0;
while (l1 != NULL || l2 != NULL) {
if (l1 != NULL) {
addon += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
addon += l2->val;
l2 = l2->next;
}
update(&ret, &cur, addon % 10);
addon /= 10;
}
if (addon != 0) {
update(&ret, &cur, addon % 10);
}
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment