2. 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.
除了0的情况外,链表不包括任何的前导0

例子如下:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 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) {
        ListNode *tmp = new ListNode(0);
        ListNode *res = tmp;
        int ful=0;
        int first = 0;
        while(l1 != NULL || l2 != NULL){
            if(first++){
                //若仍有数字,则新建节点
                tmp->next = new ListNode(0);
                tmp = tmp->next;
            }
            int num1 = (l1 == NULL)? 0 : l1->val;
            int num2 = (l2 == NULL)? 0 : l2->val;
            int sum = num1 + num2 + ful;
            
            ful = sum / 10;
            tmp->val = sum % 10;
            
            l1 = (l1 == NULL)? l1 : l1->next;
            l2 = (l2 == NULL)? l2 : l2->next;
        }
        if(ful){
            tmp->next = new ListNode(1);
        }
        return res;
    }
};
参考自https://www.cnblogs.com/aprilcheny/p/4823654.html
里面的三目运算令人眼前一亮

你可能感兴趣的:(2. Add Two Numbers)