【中级算法】6.两数相加

题目:

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

 解法:

/**
 * 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) {
        if(l1 == NULL){
            return l2;
        }
        if(l2 == NULL){
            return l1;
        }
        
        ListNode * head = NULL;
        ListNode * pre = NULL;
        int carry = 0;
        while(l1&&l2){
            ListNode * newNode = new ListNode((l1->val + l2->val + carry)%10);
            carry = (l1->val + l2->val + carry)/10;
            if(head == NULL){
                head = newNode;
                pre = head;
            }else{
                pre->next = newNode;
                pre = newNode;
            }
            l1 = l1->next;
            l2 = l2->next;
        }
        
        while(l1){
            ListNode * newNode = new ListNode((l1->val + carry)%10);
            carry = (l1->val + carry)/10;
            pre->next = newNode;
            pre = newNode;
            l1 = l1->next;
        }
        
        while(l2){
            ListNode * newNode = new ListNode((l2->val + carry)%10);
            carry = (l2->val + carry)/10;
            pre->next = newNode;
            pre = newNode;
            l2 = l2->next;
        }
        
        if(carry > 0){
            ListNode * newNode = new ListNode(carry);
            pre->next = newNode;
            pre = newNode;
        }
                
        return head;
    }
};

  

猜你喜欢

转载自www.cnblogs.com/mikemeng/p/9206959.html