Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Output: 7 -> 0 -> 8
//C Program: Add Two Numbers
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int val;
struct ListNode* q = l1;
struct ListNode* p;
while (l1&&l2)
{
p = l1;
val = l1->val + l2->val;
l1->val = val % 10;
if (val >= 10)
{
if (!l1->next)
{
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 0;
l1->next->next = NULL;
if (!l2->next)
{
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 0;
l2->next->next = NULL;
}
}
l1->next->val += 1;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1&&l1->val>=10)
{
l1->val %= 10;
if (!l1->next)
{
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 1;
l1->next->next = NULL;
break;
}
l1->next->val += 1;
l1 = l1->next;
}
if (l2)
{
p->next = l2;
}
return q;
}
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int val;
struct ListNode* q = l1;
struct ListNode* p;
while (l1&&l2)
{
p = l1;
val = l1->val + l2->val;
l1->val = val % 10;
if (val >= 10)
{
if (!l1->next)
{
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 0;
l1->next->next = NULL;
if (!l2->next)
{
l2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l2->next->val = 0;
l2->next->next = NULL;
}
}
l1->next->val += 1;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1&&l1->val>=10)
{
l1->val %= 10;
if (!l1->next)
{
l1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
l1->next->val = 1;
l1->next->next = NULL;
break;
}
l1->next->val += 1;
l1 = l1->next;
}
if (l2)
{
p->next = l2;
}
return q;
}
No comments:
Post a Comment