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.
思路:
- 新建链表cur
- L1,L2两个链表从头到后按位相加,结果插入新链表
- 为了避免两个输入链表同时为空,我们建立一个dummy结点,将两个结点相加生成的新结点按顺序加到dummy结点之后,由于dummy结点本身不能变,所以我们用一个指针cur来指向新链表的最后一个结点
- 循环条件,只要一个不为空就行,取当前结点值的时候,先判断一下,若为空则取0,否则取结点值。
- 然后把两个结点值相加,同时还要加上进位carry。然后更新carry,直接 sum/10 即可,然后以 sum%10 为值建立一个新结点,连到cur后面,然后cur移动到下一个结点
- 最高位的进位问题要最后特殊处理一下,若carry为1,则再建一个值为1的结点
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1), *cur = dummy;
int carry = 0;
while (l1 || l2) {
int val1 = l1 ? l1->val : 0;
int val2 = l2 ? l2->val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
if (carry) cur->next = new ListNode(1);
return dummy->next;
}
};