题意:给出两个由链表表示的数的逆序形式,求和,并按照输入的形式给出链表头结点。
思路:链表基础题。
/**
* 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* h = new ListNode(0);
ListNode* p = h;
int sum = 0;
while (l1 != NULL || l2 != NULL) {
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->val;
l2 = l2->next;
}
p->next = new ListNode(sum%10);
p = p->next;
sum /= 10;
}
if (sum > 0)
p->next = new ListNode(sum);
return h->next;
}
};