You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
基本链表操作,也是很多面试延伸问题的基础。需要考虑到的主要有两件事。
(1)l1, l2长度各异,考虑循环结束的分类情况;
(2)当l1和l2都读取完毕,不要忘了还有进位的可能。
我的粗糙初级代码,就是最直接的分类讨论。
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res = new ListNode(0);
ListNode *l3 = res;
int sum, flag = 0;
// l3从res下一位开始计数,相当于我留了个表头,所以return res->next
while (l1 != NULL && l2 != NULL) {
ListNode *temp = new ListNode(0);
sum = l1->val + l2->val + flag;
temp->val = sum % 10;
l3->next = temp;
l3 = l3->next;
l1 = l1->next;
l2 = l2->next;
if (sum > 9) flag = 1;
else flag = 0;
}
// l1和l2长度相等同时结束的时候
if (l1 == NULL && l2 == NULL) {
if (flag == 1) {
ListNode *temp = new ListNode(0);
temp->val = 1;
l3->next = temp;
}
return res->next;
}
// l1更长,l2结束后对l1剩下部分的讨论
if (l1) {
while (l1) {
ListNode* temp = new ListNode(0);
sum = l1->val + flag;
temp->val = sum % 10;
l3->next = temp;
l3 = l3->next;
l1 = l1->next;
if (sum > 9) flag = 1;
else flag = 0;
}
if (flag == 1) {
ListNode *temp = new ListNode(0);
temp->val = 1;
l3->next = temp;
}
return res->next;
}
// l2更长,l1结束后对l2剩下部分的讨论
if (l2) {
while (l2) {
ListNode* temp = new ListNode(0);
sum = l2->val + flag;
temp->val = sum % 10;
l3->next = temp;
l3 = l3->next;
l2 = l2->next;
if (sum > 9) flag = 1;
else flag = 0;
}
if (flag == 1) {
ListNode *temp = new ListNode(0);
temp->val = 1;
l3->next = temp;
}
return res->next;
}
return res->next;
}
改进版写法,完全可以写的更简便一点:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *res = new ListNode(0);
ListNode *l3 = res;
int carry = 0;
while (true) {
if (l1 != NULL) {
carry += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
carry += l2->val;
l2 = l2->next;
}
l3->val = carry % 10;
carry = carry / 10;
//这个判断条件包含了所有情况
if (l1 != NULL || l2 != NULL || carry == 1) {
l3 = (l3->next = new ListNode(0));
//先申请新的空间给l3->next,再移动l3.
}
else break;
}
return res;
}
同样的代码,写法优化后篇幅节约了很多。