链表模拟
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto dummy=new ListNode(-1); //虚拟头节点,统一所有节点的操作
auto cur=dummy; //当前操作的尾节点
int t=0;
while(l1 || l2 || t){ //注意最后一位的进位
if(l1)t+=l1->val,l1=l1->next;
if(l2)t+=l2->val,l2=l2->next;
cur=cur->next=new ListNode(t%10);
t/=10;
}
return dummy->next;
}
};