題目來自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;
}