Leetcode 2. Add Two Numbers

Lintcode 167. 链表求和

Posted by Olivia Liu on November 6, 2019 | 阅读:

Description

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.

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

Examples

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Answer

Add two numbers at the same position of each list and use another variable to store the carry.

Time Complexity

O(n)

Code

C++

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(!l1) return l2;
        if(!l2) return l1;
        int c = 0;
        ListNode *head = new ListNode(0);
        ListNode *ptr = head;
        while(1)
        {
            if(l1)
            {
                c += l1->val;
                l1 = l1->next;
            }
            if(l2)
            {
                c+= l2->val;
                l2 = l2->next;
            }
            ptr->val = c % 10;
            c /= 10;
            if(l1 || l2 || c != 0)
                ptr = (ptr->next = new ListNode(0));
            else break;
        }
        return head;
    }
};