您的位置:首页 > 其它

[LeetCode] Add Two Numbers

2014-11-24 08:51 351 查看
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

这题虽然归类到Medium 但是难度不大,只是要考虑的东西有点多,比如:两个list不一定一样长,进位这两个问题。

因为两个数字是逆序存到链表里的,所以这大大简化了问题难度,因为只需要向着链表遍历方向往前进位就可以了。

void addIter(ListNode *l1, ListNode *l2, ListNode *prev, int carry) {
if (!l1 && !l2 && carry == 0) return;
ListNode *node;
int val = 0;
if (l1) {
val += l1->val;
}
if (l2) {
val += l2->val;
}
val += carry;
carry = val / 10;
val = val % 10;

node = new ListNode(val);
if (prev) {
prev->next = node;
}

addIter(l1 ? l1->next : NULL, l2 ? l2->next : NULL, node, carry);
}

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *ret = new ListNode(0);
addIter(l1, l2, ret, 0);
return ret->next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: