跳到主要内容

445. 两数相加 II(Medium)

Python示例

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
stack1, stack2 = [], []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
dummpyHead = ListNode(None)
digit = 0
while stack1 or stack2:
a = stack1.pop() if stack1 else 0
b = stack2.pop() if stack2 else 0
s = a + b + digit
node = ListNode(s % 10)
digit = s // 10
node.next = dummpyHead.next
dummpyHead.next = node
if digit > 0:
node = ListNode(digit)
node.next = dummpyHead.next
dummpyHead.next = node
return dummpyHead.next
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var stack1, stack2 []int
for l1 != nil {
stack1 = append(stack1, l1.Val)
l1 = l1.Next
}
for l2 != nil {
stack2 = append(stack2, l2.Val)
l2 = l2.Next
}

var cur *ListNode
var a, b int
carry := 0
aLen, bLen := len(stack1), len(stack2)
for aLen != 0 || bLen != 0 {
if aLen > 0 {
a = stack1[aLen - 1]
aLen--
} else {
a = 0
}

if bLen > 0 {
b = stack2[bLen - 1]
bLen--
} else {
b = 0
}

node := &ListNode{Val: (a + b + carry) % 10}
carry = (a + b + carry) / 10
node.Next = cur
cur = node
}

if carry != 0 {
node := &ListNode{Val: carry}
node.Next = cur
cur = node
}
return cur
}