leetcode2.两数相加
leetcode两数相加https://leetcode-cn.com/problems/add-two-numbers/submissions/
此题注意分配内存不能用malloc()据说是内存对齐错误,我也不是很清楚;
/**
* 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 temp = 0;
struct ListNode *q = new ListNode(0);
struct ListNode *p = q;
while ((l1 != NULL) && (l2 != NULL)) {
struct ListNode *l3 = new ListNode(0);
l3->val = (l1->val + l2->val + temp) % 10;
temp = (l1->val + l2->val + temp) / 10;
p->next = l3;
p = p->next;
l1 = l1->next;
l2 = l2->next;
}
if (l1 != NULL) {
int f=0;
while (l1 != NULL) {
f=(l1->val + temp) / 10;
l1->val = (l1->val + temp) % 10;
temp=f;
p->next = l1;
l1 = l1->next;
p = p->next;
}
}
else if (l2 != NULL) {
int f=0;
while (l2 != NULL) {
f=(l2->val + temp) / 10;
l2->val = (l2->val + temp) % 10;
temp=f;
p->next = l2;
l2 = l2->next;
p = p->next;
}
}
if (temp == 1) {
struct ListNode *l3 = new ListNode(0);
l3->next = NULL;
l3->val = 1;
p->next = l3;
p = p->next;
}
q = q->next;
return q;
}
};