[
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
]
链表操作,C语言基本功。考虑进位。求余求模的基本操作。新链表节点函数AddInL3提取出来复用。
这题其实只有简单题的难度,后面中等题可比这题难多了。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* head;
struct ListNode* end;
void AddInL3(int temp) {
struct ListNode* new;
new = (struct ListNode*)malloc(sizeof(struct ListNode));
new->val = temp;
new->next = NULL;
if (head == NULL) {
head = new;
end = new;
} else {
end->next = new;
end = new;
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int addflag = 0;
int temp;
head = NULL;
end = NULL;
while (l1 || l2) {
temp = addflag;
if (l1) {
temp += l1->val;
l1 = l1->next;
}
if (l2) {
temp += l2->val;
l2 = l2->next;
}
addflag = temp / 10;
temp = temp % 10;
//printf("temp=%d,addflag=%d\n",temp,addflag);
AddInL3(temp);
}
if (addflag) {
AddInL3(addflag);
}
return head;
}
扫描二维码关注公众号,回复:
9170541 查看本文章