Description
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *l1Head = l1;
ListNode *l2Head = l2;
ListNode *addedHead = NULL;
ListNode *item = NULL;
int l1Val = 0;
int l2Val = 0;
int sumVal = 0;
bool bDeca = false;
bool bQuitL1 = false;
bool bQuitL2 = false;
while (true) {
if (l1Head) {
l1Val = l1Head->val;
l1Head = l1Head->next;
} else {
l1Val = 0;
bQuitL1 = true;
}
if (l2Head) {
l2Val = l2Head->val;
l2Head = l2Head->next;
} else {
l2Val = 0;
bQuitL2 = true;
}
if (bQuitL1 && bQuitL2 && !bDeca) {
break;
}
if (bDeca) {
sumVal += 1;
// reset bDeca
bDeca = false;
}
sumVal += l1Val + l2Val;
if (0 != (sumVal / 10)) {
bDeca = true;
sumVal = sumVal % 10;
}
item = new ListNode(sumVal);
// reset sumVal
sumVal = 0;
if (NULL == addedHead) {
addedHead = item;
} else {
ListNode *p = addedHead;
while (p->next) {
p = p->next;
}
p->next = item;
}
}
return addedHead;
}
};
汇总
性能一般,需要优化。