题目
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 ->
想法
定义一个进位变量,创建一个链表。 仿照数学中对两个整数的相加,将和放在新建的链表里。
代码struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode * sum = malloc( sizeof( struct ListNode ) ), *coSum = sum;
int carry = 0;
while( 1 )
{
coSum->val = ( l1 ? 0 : l1->val ) + ( l2 ? 0 : l2->val ) + carry;
l1 = l1 ? NULL : l1->next;
l2 = l2 ? NULL : l2->next;
carry = coSum->val / 10;
coSum->val %= 10;
if( l1 || l2 || carry != 0 )
{
coSum->next = malloc( sizeof( struct ListNode ) );
coSum = coSum->next;
}
else
{
coSum->next = NULL;
return sum;
}
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode * sum = malloc( sizeof( struct ListNode ) ), *coSum = sum;
int carry = 0;
while( 1 )
{
coSum->val = ( l1 ? 0 : l1->val ) + ( l2 ? 0 : l2->val ) + carry;
l1 = l1 ? NULL : l1->next;
l2 = l2 ? NULL : l2->next;
carry = coSum->val / 10;
coSum->val %= 10;
if( l1 || l2 || carry != 0 )
{
coSum->next = malloc( sizeof( struct ListNode ) );
coSum = coSum->next;
}
else
{
coSum->next = NULL;
return sum;
}
}
}