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
需要注意对进位的维护,如果最后加完时还有进位,应该再开辟一个新结点将进位加进去。
/**
* 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(0);
ListNode *p=&dummy;
int sum,val,cn=0;
while(l1||l2){
sum=cn+(l1?l1->val:0)+(l2?l2->val:0);
val=sum%10;
cn=sum/10;
p->next=new ListNode(val);
p=p->next;
if(l1) l1=l1->next;
if(l2) l2=l2->next;
}
if(cn){
p->next=new ListNode(cn);
p=p->next;
}
return dummy.next;
}
};