/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode *l1_temp = l1, *l2_temp = l2, *head ,*head_temp;
head_temp = head = (ListNode*) malloc(sizeof(ListNode));
head -> next = NULL;
while(l1_temp != NULL || l2_temp != NULL){
// (l1_temp != NULL && l2_temp != NULL) 写法复杂
head_temp -> next = (ListNode*) malloc(sizeof(ListNode));
head_temp = head_temp -> next;
head_temp -> next = NULL;
int x = (l1_temp == NULL) ? 0 : l1_temp -> val;
int y = (l2_temp == NULL) ? 0 : l2_temp -> val;
head_temp -> val = (x + y + carry) % 10;
carry = (x + y + carry) / 10;
if(l1_temp != NULL) l1_temp = l1_temp -> next;
if(l2_temp != NULL) l2_temp = l2_temp -> next;
}
// easy to forget
if(carry){
head_temp -> next = new ListNode(carry);
}
return head -> next;
}
};
注意最后进位不为0时,还需继续插入节点。
这个写法比较简洁,如用while(l1_temp != NULL && l2_temp != NULL)
的写法,会增加20行左右。
本文介绍了一种解决两数相加问题的链表实现方法。通过定义单链表结构,采用迭代方式处理两个链表数值的相加运算,并妥善处理进位问题。文章详细展示了如何在链表尾部添加新节点以处理最后的进位情况。
1077

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



