题目来自LeetCode:
https://leetcode-cn.com/problems/add-two-numbers/description/
注意几点:
- 链表对应结点相加时增加前一个结点的进位,并保存下一个结点的进位;
- 两个链表长度不一致时,要处理较长链表剩余的高位和进位计算的值;
- 如果最高位计算时还产生进位,则还需要添加一个额外结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode * p1,* p2,* p3,* l3, *temp;
p1 = l1;
p2 = l2;
l3 = (struct ListNode *)malloc(sizeof(struct ListNode));
p3 = l3;
int carry = 0; //进位
int sum;
while (p1 && p2) {
temp = (struct ListNode *)malloc(sizeof(struct ListNode)); //创建新节点
p3->next = temp;
temp->next = NULL;
sum = p1->val + p2->val + carry;
if(sum >= 10) {
carry = 1;
temp->val = sum%10;
}else {
carry = 0;
temp->val = sum;
}
p1=p1->next;
p2=p2->next;
p3=p3->next;
}
while (p1) {
temp = (struct ListNode *)malloc(sizeof(struct ListNode)); //创建新节点
p3->next = temp;
temp->next = NULL;
sum = p1->val + carry;
if(sum >= 10) {
carry = 1;
temp->val = sum%10;
}else {
carry = 0;
temp->val = sum;
}
p1=p1->next;
p3=p3->next;
}
while ( p2) {
temp = (struct ListNode *)malloc(sizeof(struct ListNode)); //创建新节点
p3->next = temp;
temp->next = NULL;
sum = p2->val + carry;
if(sum >= 10) {
carry = 1;
temp->val = sum%10;
}else {
carry = 0;
temp->val = sum;
}
p2=p2->next;
p3=p3->next;
}
if(carry == 1) {
temp = (struct ListNode *)malloc(sizeof(struct ListNode)); //创建新节点
p3->next = temp;
temp->next = NULL;
temp->val = 1;
}
return l3->next;
}