Lintcode: Add Two Numbers

时间:2023-03-08 17:19:35
Lintcode: Add Two Numbers

C++

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
ListNode *ptr1 = l1, *ptr2 = l2;
ListNode *result = new ListNode(-);
ListNode *pre = result;
int carry = , val = ;
while (ptr1 != NULL || ptr2 != NULL) {
int val1 = ptr1 == NULL?:ptr1->val;
int val2 = ptr2 == NULL?:ptr2->val;
int sum = val1 + val2 + carry;
val = sum;
carry = sum/;
pre->next = new ListNode(val);
pre = pre->next;
if (ptr1!=NULL)
{
ptr1 = ptr1->next;
}
if (ptr2!=NULL)
{
ptr2 = ptr2->next;
}
}
if (carry == ) {
pre->next = new ListNode();
}
return result->next;
}
};