LeetCode系列之(2)两数相加
题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
我的解题思路
其实拿到这个题,经过分析,该题的难度在于链表这个数据结构,如何灵活遍历链表,生成一个新的链表是该题的难点,因此主要就是围绕如何遍历链表和生成新链表来解答该题。
@python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
count1 = 0
count2 = 0
list_1 = []
list_2 = []
while l1:
list_1.append(l1.val)
l1 = l1.next
count1 += 1
while l2:
list_2.append(l2.val)
l2 = l2.next
count2 += 1
list_1 = [str(list_1[count1-1-i])for i in range(count1)]
list_2 = [str(list_2[count2-1-i])for i in range(count2)]
value_1 = int("".join(list_1))
value_2 = int("".join(list_2))
list_3 = list(str(value_1+value_2))
count3 = len(list_3)
head = None
for i in range(count3):
i = count3 - 1 - i
temp = ListNode(list_3[i])
if head:
curr = head
while curr.next:
curr = curr.next
curr.next = temp
else:
head = temp
return head
官方题解思路
就像你在纸上计算两个数字的和那样,我们首先从最低有效位也就是列表 l1l1l1 和 l2l2l2 的表头开始相加。由于每位数字都应当处于 0…90 \ldots 90…9 的范围内,我们计算两个数字的和时可能会出现“溢出”。例如,5+7=125 + 7 = 125+7=12。在这种情况下,我们会将当前位的数值设置为 222,并将进位 carry=1carry = 1carry=1 带入下一次迭代。进位 carrycarrycarry 必定是 000 或 111,这是因为两个数字相加(考虑到进位)可能出现的最大和为 9+9+1=199 + 9 + 1 = 199+9+1=19。
@Java
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
反思
掌握链表数据结构,如何遍历,如何生成,如何删除,如何插入时后续需要考虑的重点。