LeetCode OJ的第四题,如果有问题或者给我指点欢迎来信讨论ms08.shiroh@gmail.com
题目描述
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
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
也就是给两个链表,每个链表代表一个非负数字,链表是按数字反方向存储,如642表示为链表就是2->4->6.
返回一个链表代表两数相加的结果(当然也是方向存储的)
思路
这道题目思路很简单,直接加就好了,注意判断好链表为空的情况以及进位的情况
代码
Python
def addTwoNumbers(self, l1, l2):
if not l1 or not l2:
return l2 if not l1 else l1
carry = (l1.val + l2.val) / 10
# result link
res = ListNode((l1.val + l2.val) % 10)
# store tmp res
tmp_res = res
while l1.next and l2.next:
l1 = l1.next
l2 = l2.next
# add to link
tmp_res.next = ListNode((l1.val + l2.val + carry) % 10)
carry = (l1.val + l2.val + carry) / 10
tmp_res = tmp_res.next
# if l1 still left
while l1.next:
l1 = l1.next
tmp_res.next = ListNode((l1.val + carry) % 10)
carry = (l1.val + carry) / 10
tmp_res = tmp_res.next
# if l2 still left
while l2.next:
l2 = l2.next
tmp_res.next = ListNode((l2.val + carry) % 10)
carry = (l2.val + carry) / 10
tmp_res = tmp_res.next
# if stall exist carry
if carry != 0:
tmp_res.next = ListNode(carry)
tmp_res = tmp_res.next
return res
C++
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if (l1 == NULL || l2 == NULL)
return l1 == NULL ? l2 : l1;
int carry = ((l1->val + l2->val) / 10);
ListNode* res = new ListNode((l1->val + l2->val) % 10);
ListNode* tmp_res = res;
while (l1->next != NULL && l2->next != NULL) {
l1 = l1->next;
l2 = l2->next;
// 添加结点
tmp_res->next = new ListNode(((l1->val + l2->val + carry) % 10));
carry = (l1->val + l2->val + carry) / 10;
tmp_res = tmp_res->next;
}
// 如果l1比较长,还存在剩余部分
while (l1->next != NULL) {
l1 = l1->next;
// 添加结点
tmp_res->next = new ListNode(((l1->val + carry) % 10));
carry = (l1->val + carry) / 10;
tmp_res = tmp_res->next;
}
// 若果l2比较长,还存在剩余部分
while (l2->next != NULL) {
l2 = l2->next;
// 添加结点
tmp_res->next = new ListNode(((l2->val + carry) % 10));
carry = (l2->val + carry) / 10;
tmp_res = tmp_res->next;
}
// 如果做完加法仍然有进位存在
if (carry != 0){
tmp_res->next = new ListNode(carry);
tmp_res = tmp_res->next;
}
return res;
}
};