您的位置:首页 > 其它

Add two numbers [LeetCode]

2013-11-25 15:51 405 查看
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

Summary: Be careful about the last carry.

ListNode * handler(int sum, int * carry, ListNode * result, ListNode * * new_head){
if(result == NULL){
result = new ListNode(sum % 10);
(*new_head) = result;
}else{
result->next = new ListNode(sum % 10);
result = result->next;
}

(*carry) = sum / 10;
return result;
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode * new_head = NULL;
ListNode * result = NULL;
int carry = 0;
while(l1 != NULL || l2 != NULL){
if(l1 == NULL){
int sum = l2->val + carry;
result = handler(sum, &carry, result, &new_head);
l2 = l2->next;
continue;
}

if(l2 == NULL){
int sum = l1->val + carry;
result = handler(sum, &carry, result, &new_head);
l1 = l1->next;
continue;
}

int sum = l1->val + l2->val + carry;
result = handler(sum, &carry, result, &new_head);
l1 = l1->next;
l2 = l2->next;
}

if(carry != 0 )
result->next = new ListNode(carry);

return new_head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: