LeetCode: 2. Add Two Numbers
/**
* 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 )
{
int carry = 0;// 是否需要进位
ListNode * tail = new ListNode(0);
ListNode * ptr = tail;// 当前指针
while(l1 != NULL || l2 != NULL){
int val1 = 0,val2 = 0;
if (l1 != NULL){
val1 = l1 -> val;
l1 = l1 -> next;
}
if (l2 != NULL){
val2 = l2 -> val;
l2 = l2 -> next;
}
ptr -> val = (val1 + val2 + carry) % 10 ;
carry = ( val1 + val2 + carry )/ 10;
// 增加
if (l1 != NULL || l2 != NULL){
ptr -> next = new ListNode(0);
ptr = ptr -> next;
}
}
if (carry == 1){
ptr -> next = new ListNode(1);
}
return tail;
}
};