2. Add Two Numbers
Question
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.
Solution
- 基于链表的运算
- 逐位加法:计算当前位,更新进位,更新操作数
- 当前位有至少一个操作数 or 有进位的时候,结果的当前位需要进行计算
- 即
l1!=NULL||l2!=NULL||carry==1
- 即
- 链表需要有一个头部指针(result)和一个滑动指针(curr)
- 更为简洁地写法,使用三目运算符和
%操作- C++可以直接将指针作为逻辑表达式,NULL返回false,非NULL返回true
更为简洁地写法:
/**
* 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) {
ListNode *sum = new ListNode(0);
ListNode *curr = sum;
int carry = 0;
while (l1!=NULL || l2!=NULL || carry!=0) {
curr->next = new ListNode(0);
curr = curr->next;
curr->val = (l1?l1->val:0)+(l2?l2->val:0)+carry;
carry = curr->val>=10?1:0;
curr->val = curr->val%10;
l1 = l1?l1->next:l1;
l2 = l2?l2->next:l2;
}
return sum->next;
}
};
/**
* 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* result = new ListNode(0);
ListNode* curr = fresult;
for(;l1!=NULL||l2!=NULL||carry==1;) {
// 如果满足条件,为结果新创建一位
curr->next = new ListNode(0);
curr = curr->next;
curr->val += carry;
if (l1!=NULL) {
curr->val += l1->val;
l1 = l1->next;
}
if (l2!=NULL) {
curr->val += l2->val;
l2 = l2->next;
}
if (curr->val >= 10) {
carry = 1;
curr->val -= 10;
}
else {
carry = 0;
}
}
return result->next;
}
};