【链接】https://leetcode-cn.com/problems/add-two-numbers/
题目:
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.
思路:
1,注意这里是链表结构,所以题目点出需要逆序计算。
2,注意头节点是一个虚节点,不存放值,目的是不需要单独处理head,方便。
3,注意进位,计算到最后一位,要判断进位,这是最后一点小细节。
代码:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == nullptr || l2 == nullptr) return NULL;
ListNode *res = new ListNode();
ListNode * cur = res;
int carry = 0;
while(l1 != NULL || l2 != NULL){
int x,y;
if(l1 == NULL){
x = 0;
}else{
x = l1->val;
}
if(l2 == NULL){
y = 0;
}else{
y = l2->val;
}
cur->next = new ListNode((x+y+carry)%10);
cur = cur->next;
carry = (x+y+carry)/10;
if(l1 != nullptr) l1 = l1->next;
if(l2 != nullptr) l2 = l2->next;
}
if(carry != 0){
cur->next = new ListNode(carry%10);
}
return res->next;
}