原题
https://leetcode.cn/problems/add-two-numbers/
思路
模拟法,从左向右相加,如果和超过10就进位。
复杂度
时间:O(n)
空间:O(1)
Python代码
# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
pre = ListNode(0)
dummy = pre
carry = 0
while l1 or l2:
n1 = l1.val if l1 is not None else 0
n2 = l2.val if l2 is not None else 0
# 当前位数字
val = (n1 + n2 + carry) % 10
# 进位数字
carry = (n1 + n2 + carry) // 10
# 生成节点
pre.next = ListNode(val)
# 后移一位
pre = pre.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
# 如果carry不为0,加上carry
if carry > 0:
pre.next = ListNode(carry)
return dummy.next
Go代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
dummy := ListNode{}
// 当前指针
cur := &dummy
carry := 0
for l1 != nil || l2 != nil || carry != 0 {
total := carry
if l1 != nil {
total += l1.Val
l1 = l1.Next
}
if l2 != nil {
total += l2.Val
l2 = l2.Next
}
cur.Next = &ListNode{Val: total % 10}
// 进位
carry = total / 10
// 移动指针
cur = cur.Next
}
return dummy.Next
}
博客围绕LeetCode上两数相加问题展开,采用模拟法,从左向右相加,和超10则进位。分析复杂度,时间和空间均为O(n),并给出Python和Java代码求解该问题。

被折叠的 条评论
为什么被折叠?



