2. Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

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

============

题目:两个链表从head节点对齐,开始按节点相加,并向右进位

思路:

设置一个进位标志carray  = 0,两个链表节点指针l1,l2分别指向list1和list2

当l1和l2的当前位置都有节点时,将两个节点的值相加放入list1中,

当list1比list2长时,对list1中剩余节点单独判断carray进位标志

反之,当list2比list1长时,对list2中的剩余节点单独判断carray进位标志

最后还要判断carray==1?   决定是否new一个新的节点

code如下:

/**
 * 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==nullptr) return l2;
        if(l2==nullptr) return l1;
        int carray = 0;
        ListNode *prev = nullptr;
        ListNode *head = l1;
        //showList(l1);
        //showList(l2);
        while(l1 && l2){
            int tmp = l1->val + l2->val + carray;
            carray = tmp>9 ? 1:0;
            l1->val = tmp%10;
            prev = l1;
            l1 = l1->next;
            l2 = l2->next;
        }
        while(l1){
            int tmp = l1->val+carray;
            carray = tmp>9 ? 1:0;
            l1->val = tmp%10;
            prev = l1;
            l1 = l1->next;
        }
        while(l2){
            int tmp = l2->val+carray;
            carray = tmp>9 ? 1:0;
            l2->val = tmp%10;
            prev->next = l2;
            prev = l2;
            l2 = l2->next;
        }
        if(carray==1) prev->next = new ListNode(1);
        return head;
    }
};
原文地址:https://www.cnblogs.com/li-daphne/p/5607069.html