Add Two Numbers
Difficult:Medium
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 -> 8
题目就是说要实现两个逆序存储在链表中的数进行相加,相加后的结果也使用逆序链表存储。
对于每一位,只要对相应的位(个十百千等)进行相加,并加上前一位的进位,结果大于等于10则要进位到下一位,并把该结果的值模10。
相加的两位如果其中一位不存在则直接使用有值的一位即可,如100+25=125中的百位的计算。
两数相加可能会超过原有两数的位数,例如500+500=1000,则在计算完百位的5+5后依然要进位。
struct ListNode {
int val;
struct ListNode *next;
};
ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
//判断是否为空,当然题目中也说明了会输入非空的链表,这里进不进行判断无所谓
if (l1 == NULL && l2 == NULL)
return NULL;
else if (l1 == NULL)
return l2;
else if (l2 == NULL)
return l1;
ListNode *result = (ListNode *)malloc(sizeof(ListNode));//结果的头结点
ListNode *p = result;
bool carry = false;//是否有进位
int sum = l1->val + l2->val;//第一位计算
sum <10 ? result->val = sum : (carry = true, result->val = sum % 10);
while (l1->next != NULL || l2->next != NULL){//当两个链表不都遍历完前一直进行计算
p = p->next = (ListNode *)malloc(sizeof(ListNode));
p->val = 0;
if (l1->next != NULL){//要计算的位不为空则参与计算
l1 = l1->next;
p->val += l1->val;
}
if (l2->next != NULL){//要计算的位不为空则参与计算
l2 = l2->next;
p->val += l2->val;
}
if (carry)//有进位
p->val++;
p->val < 10 ? carry = false : (p->val = p->val % 10, carry = true);//判断相应的两位相加完后是否有进位
}
if (carry){//最大的两位计算完后有进位的情况
p = p->next = (ListNode *)malloc(sizeof(ListNode));
p->val = 1;
}
p->next = NULL;
return result;
}
本文介绍了一种算法,用于解决两个逆序存储在链表中的非负整数相加的问题。通过遍历两个链表并逐位相加,考虑进位情况,最终将结果以逆序链表形式返回。
177

被折叠的 条评论
为什么被折叠?



