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
1 - 简单的链表操作
2 - 活用三元表达式简化代码
/**
* 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 dummy(-1);
ListNode *cur = &dummy;
int carry = 0;//进位
for(;l1!=nullptr||l2!=nullptr;l1=(l1==nullptr)?nullptr:l1->next,l2=(l2==nullptr)?nullptr:l2->next){
const int a = (l1==nullptr)?0:l1->val;
const int b = (l2==nullptr)?0:l2->val;
int value = (a+b+carry)%10;
carry = (a+b+carry>=10)?1:0;
cur->next = new ListNode(value);
cur = cur -> next;
}
//如果最后一次相加产生了进位,还需要生成一个新节点
if(carry==1) cur->next = new ListNode(carry);
return dummy.next;
}
};