版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40921797/article/details/82710946
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路:
因为我们是按照逆序存储的,所以我们从头向后存储每个位相加的结果,再存储对应的cf进位,这个思想来源于系统对二进制相加的思路来的。
代码实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *head=(struct ListNode *)malloc(sizeof(struct ListNode));
//自己开辟一个链表,提供结果返回,动态开辟可以返回
struct ListNode *cur;
int cf = 0;
cur = head;
//如果有一个链表无节点则不需要直接返回另一个即可
if(l1 == NULL&&l2 != NULL)return l2;
else if(l2 == NULL&&l1 != NULL)return l1;
while(l1 != NULL&&l2 != NULL)//得出这个整数
{
cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
cur->next->val = (l1->val + l2->val + cf) % 10;
//存储当前位
cur->next->next = NULL;
cf=(l1->val + l2->val + cf) / 10;
//保存进位位
cur = cur->next;
l1 = l1->next;
l2 = l2->next;
}
if(l1 != NULL)
//如果l2结束跳出的循环,还是要将cf和l1上剩余节点相加。
while(l1 != NULL)
{
cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
cur->next->val = (l1->val + cf) % 10;
cur->next->next = NULL;
cf = (l1->val + cf) / 10;
cur = cur->next;
l1 = l1->next;
}
else
//和l1的循环同理
while(l2 != NULL)
{
cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
cur->next->val = (l2->val + cf) % 10;
cur->next->next = NULL;
cf = (l2->val + cf) / 10;
cur = cur->next;
l2 = l2->next;
}
//如果最后还有cf进位,则要单独再开辟一个节点存储
if(cf!=0)
{
cur->next = (struct ListNode *)malloc(sizeof(struct ListNode));
cur->next->val = cf;
cur->next->next = NULL;
}
else{
cur->next = NULL;
}
cur = head->next;
free(head);
return cur;
}