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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


这道题总的来说不是很难。只需要历遍两个链表,将对应的值相加就可以了。

在计算的过程中要把进位计算在内,注意最后一位的进位。


下面直接贴代码:

/**
 * 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 *result, *temp1, *temp2;
        result = temp1 = NULL;
        int carry = 0;  // 刚开始进位为0
        while (l1 != NULL && l2 != NULL) {
            temp2 = new ListNode((l1->val + l2->val + carry)%10);  // l1 + l2 的个位数
            if (result == NULL) {
                result = temp1 = temp2;
            } else {
                temp1->next = temp2;
            }
            temp1 = temp2;
            carry = (l1->val + l2->val + carry)/10;
            l1 = l1->next;
            l2 = l2->next;
        }
        if (l1 != NULL) {
            temp1->next = l1;
        }
        if (l2 != NULL) {
            temp1->next = l2;
        }
        int i;
        while (temp1-> next != NULL) {
            temp1 = temp1->next;
            i = temp1->val;
            temp1->val = (i + carry)%10;
            carry = (i + carry)/10;
        }
        if (carry != 0) {
            temp2 = new ListNode(carry);
            temp1->next = temp2;
        }
        return result;
    }
};

你可能感兴趣的:(算法分析,Leetcode)