力扣 | 2.两数相加
题目截图
官方方法
总共有三个链表,l1,l2和最后的结果链表。l1和l2各自滑动对应链表各个位数支出相应的值,最后相加,将结果添加到新链表上。
唯一需要考虑的是数值相加后的进位。
先设置进位carry为0
结果相加的时候利用取模和取整来进位。
比如,8+7=15,各位留5,进位为1。
创建一个头结点head和一个移动结点p
当l1或l2存在时,新建一个结点new_point并赋值为0。然后进入判断:
若l1不存在,则只用将l2的值付给新链表。反之,亦然。若两个都存在,则当前位的值为(l1的值+l2的值)取模,进位为两者之和除10取整。,然后指针往后滑动,知道l1和l2都遍历完成
还需要注意全部遍历完成后可能还有进位,再添加一个结点,并赋值为1。
最后返回头结点。
代码如下
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = point = ListNode(0)
carry = 0
while l1 or l2:
new_point = ListNode(0)
if not l1:
sum_=l2.val+carry
new_point.val = sum_ % 10
carry = sum_ // 10
l2 = l2.next
elif not l2:
sum_ = l1.val +carry
new_point.val = sum_ % 10
carry = sum_ // 10
l1 = l1.next
else:
sum_ = l1.val + l2.val + carry
new_point.val = sum_ % 10
carry = sum_ // 10
l1 = l1.next
l2 = l2.next
point.next = new_point
point = point.next
if carry:
new_point = ListNode(1)
point.next = new_point
return head.next
完整测试代码
# Definition for singly-linked list.
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = point = ListNode(0)
carry = 0
while l1 or l2:
new_point = ListNode(0)
if not l1:
sum_=l2.val+carry
new_point.val = sum_ % 10
carry = sum_ // 10
l2 = l2.next
elif not l2:
sum_ = l1.val +carry
new_point.val = sum_ % 10
carry = sum_ // 10
l1 = l1.next
else:
sum_ = l1.val + l2.val + carry
new_point.val = sum_ % 10
carry = sum_ // 10
l1 = l1.next
l2 = l2.next
point.next = new_point
point = point.next
if carry:
new_point = ListNode(1)
point.next = new_point
return head.next
class Linked_List:
def create_linked_list(self, nums):
if len(nums) == 0:
return None
head = ListNode(nums[0])
cur = head
for i in range(1, len(nums)):
cur.next = ListNode(nums[i])
cur = cur.next
return head
def print_linked_list(list_node):
if list_node is None:
return
cur = list_node
while cur:
print(cur.val, '->', end=' ')
cur = cur.next
print('null')
class main:
list_1 = [2,4,3]
list_2 = [5,6,4]
solution = Solution()
link_list = Linked_List()
head_1 = link_list.create_linked_list(list_1)
head_2 = link_list.create_linked_list(list_2)
answer = solution.addTwoNumbers(head_1, head_2)
print_linked_list(answer)
if __name__ == '__main__':
main()
pycharm上测试结果
简化代码版
简化代码版的思路和官方方法相差不大。
但是直接将l1和l2以及进位的问题合并考虑,并运用三元表达式简化代码量。
代码如下
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
head = p = ListNode(None)
carry = 0
while l1 or l2 or carry:
carry += (l1.val if l1 else 0) + (l2.val if l2 else 0)
p.next = ListNode(carry % 10)
p = p.next
carry = carry // 10
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return head.next