问题描述
$\textrm{LeetCode2-两数相加}$
解法
用链表的单个节点存储整数的一位,将这样两个链表相加
考虑进位,链表长度不一致,初始节点特判的问题,将代码写的尽量简洁即可
cpp code
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;
}
};
Author@Kuroko
GitHub@SuperKuroko
LeetCode@kuroko177
Last Modified: 2023-02-17 15:31