/**
* 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 preHead(0), *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}
};
上面是别人的,下面是自己的,先标记下,显示内存不对齐
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
double n;
unsigned long long int value(struct ListNode* l1){
if(!l1)
return 0;
else{
n *= 10;
unsigned long long int val = l1->val;
return n*val+value(l1->next);
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
if(!l1)
return l2;
if(!l2)
return l1;
n = 0.1;
unsigned long long int x = value(l1);
n = 0.1;
unsigned long long int y = value(l2);
unsigned long long int c = x+y;
struct ListNode *l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
l3->next = NULL;
struct ListNode *head = l3;
unsigned long long int d = c % 10;
c /= 10;
l3->val = d;
l3->next = NULL;
while(c){
d = c % 10;
c /= 10;
struct ListNode *node =(struct ListNode*)malloc(sizeof(struct ListNode));
node->val = d;
l3->next = node;
l3 = l3->next;
}
return head;
}