$\textrm{Problem Description : }$$\href{https://leetcode.cn/problems/add-two-numbers/}{\textrm{LeetCode2-两数相加}}$

用链表的单个节点存储整数的一位,将这样两个链表相加

$\textrm{Solution:}$

考虑进位,链表长度不一致,初始节点特判的问题,将代码写的尽量简洁即可

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int c = 0,x,y;
        ListNode *ans = nullptr,*p;
        while(l1 || l2)
        {
            x = (l1?l1->val:0);
            y = (l2?l2->val:0);
            x += y+c; 
            c=x/10; x%=10;
            if(ans)
            {
                p->next = new ListNode(x);
                p = p->next;
            }
            else ans = p = new ListNode(x);
            if(l1)l1 = l1->next;
            if(l2)l2 = l2->next;
        }
        if(c) p->next = new ListNode(1);
        return ans;
    }
};

$\textrm{Author}$@$\href{http://kuroko.info}{\textrm{Kuroko}}$

$\textrm{GitHub}$@$\href{https://github.com/SuperKuroko}{\textrm{SuperKuroko}}$

$\textrm{LeetCode}$@$\href{https://leetcode-cn.com/u/kuroko177/}{\textrm{kuroko177}}$

$\textrm{Last Modified: 2023-02-17 15:31}$