链表求和
version one
两个指针分别遍历两个链表,只需要注意好进位关系即可。其中c代表进位,temp代表链表中数字的临时加和。
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
if (l1 == NULL)
{
return l2;
}else if (l2 == NULL)
{
return l1;
}
int c = 0;
int temp = 0;
ListNode *head = new ListNode(0);
ListNode *p = head;
while (l1 != NULL && l2 != NULL)
{
temp = l1->val+l2->val + c;
c = temp / 10;
temp = temp % 10;
p->next = new ListNode(temp);
p = p->next;
l1 = l1->next;
l2 = l2->next;
}
while (l1 != NULL)
{
temp = l1->val + c;
c = temp / 10;
temp = temp % 10;
p->next = new ListNode(temp);
p = p->next;
l1 = l1->next;
}
while (l2 != NULL)
{
temp = l2->val + c;
c = temp / 10;
temp = temp % 10;
p->next = new ListNode(temp);
p = p->next;
l2 = l2->next;
}
if (c != 0)
{
p->next = new ListNode(c);
}
return head->next;
}