Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created September 2, 2018 03:02
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 zhangxiaomu01/6e28ce2d0741f10e1f04138d4f470871 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/6e28ce2d0741f10e1f04138d4f470871 to your computer and use it in GitHub Desktop.
This is the solution for add two numbers problem in Leetcode
/**
* 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) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment