两数相加
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
思路:
1.创建一个新链表,新链表的头部先设置为l1头部和l2头部之和。
2.遍历两个链表,只要有一个还没有遍历完就继续遍历
3.每次遍历生成一个当前节点cur的下一个节点,其值为两链表对应节点的和再加上当前节点cur产生的进位
4.更新进位后的当前节点cur的值
5.循环结束后,因为首位可能产生进位,因此如果cur.val是两位数的话,新增一个节点
6.返回头节点
由题目注释可以看出listNode这个类是用来创建链表的,默认next=None,val=0.
Definition for singly-linked list.
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(l1.val+l2.val)
current = head
while l1.next or l2.next:
l1 = l1.next if l1.next else ListNode()
l2 = l2.next if l2.next!=None else ListNode()
current.next = ListNode(l1.val+l2.val+current.val//10)
current.val = current.val%10
current = current.next
if current.val >= 10:
current.next = ListNode(current.val//10)
current.val = current.val%10
return head
改进改进:增加了空间复杂度。本以为一方为None后直接把另一个链表连上就ok了。然后,就打脸了。
然后又加了while
> [9999]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(l1.val+l2.val)
current = head
while l1.next and l2.next:
l1 = l1.next
l2 = l2.next
current.next = ListNode(l1.val+l2.val+current.val//10)
current.val = current.val%10
current = current.next
if l1.next == None and l2.next :
while l2.next:
l2 = l2.next
current.next= ListNode(l2.val+current.val//10)
current.val = current.val%10
current = current.next
current.next = l2.next
elif l2.next == None and l1.next:
while l1.next:
l1 = l1.next
current.next= ListNode(l1.val+current.val//10)
current.val = current.val%10
current = current.next
current.next = l2.next
if current.val >= 10:
current.next = ListNode(current.val//10)
current.val = current.val%10
return head
到此这篇关于python3两数相加的实现示例的文章就介绍到这了,更多相关python3两数相加内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!