You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
题目大意:链表中,每个节点表示多位数中的某一位,每个节点的value一定是单个数字,把两个链表的值相加得到一个新的链表
首先是原创的方法,代码很乱,读者可以忽视这部分,看后一部分,因为自己不会创建链表,因此返回的是输入中的某一个链表
方法:找到更长的链表,并且每次加法后覆盖其原有的value,最后针对超出的部分进行处理即可
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int c = 0;
ListNode* root_l1 = l1, *root_l2 = l2;
int len_l1 = 0, len_l2 = 0;
while(root_l1 != NULL) {++len_l1; root_l1 = root_l1->next;}
while(root_l2 != NULL) {++len_l2; root_l2 = root_l2->next;}
int length = len_l1 > len_l2 ? len_l2 : len_l1;
ListNode* root = len_l1 > len_l2 ? l1 : l2;
ListNode* head = new ListNode(-1);
head->next = root;
for(int i = 0; i < length; ++i){
int tmp = (l1->val + l2->val + c) / 10;
head->next->val = (l1->val + l2->val + c) % 10;
c = tmp;
head = head->next;
l1 = l1->next;
l2 = l2->next;
}
while(head->next != NULL && c != 0){
int tmp = (head->next->val + c) / 10;
head->next->val = (head->next->val + c) % 10;
c = tmp;
head = head->next;
}
ListNode* back = new ListNode(1);
if(head->next == NULL && c == 1){
head->next = back;
}
return root;
}
};
接下来是参考了网友的方法,代码简洁很多,思路和上面一样,代码优化的地方
- 创建链表的方式:head->next = new ListNode((l1_val + l2_val + c) % 10);
- 通过的||+循环内部if的方式,将长链表超出部分的处理也写在一个循环里面
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int c = 0;
ListNode* head = new ListNode(-1);
ListNode* root = head;
while(l1 || l2){
int l1_val = l1 != NULL ? l1->val : 0;
int l2_val = l2 != NULL ? l2->val : 0;
head->next = new ListNode((l1_val + l2_val + c) % 10);
c = (l1_val + l2_val + c) / 10;
head = head->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
if(c){
head->next = new ListNode(1);
}
return root->next;
}
};
读者有何问题,可以留言沟通,?
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。