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) {
int carry = 0;
ListNode *p, *q, *r, *head;
p = l1;
q = l2;
if (p || q){
int val = carry;
if (p)
val += p->val;
if (q)
val += q->val;
carry = val / 10;
val %= 10;
head = new ListNode(val);
p = p->next;
q = q->next;
r = head;
while (p || q || carry){
int tmp = carry;
if (p)
tmp += p->val;
if (q)
tmp += q->val;
carry = tmp / 10;
tmp %= 10;
r->next = new ListNode(tmp);
r = r->next;
if (p)
p = p->next;
if (q)
q = q->next;
}
return head;
}
return p;
}
};