给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var result: ListNode?
var currentResultNode: ListNode?
var currentL1Node = l1
var currentl2Node = l2
var out = 0
while (currentL1Node != nil || currentl2Node != nil) || out > 0 {
var l1Val = 0
var l2Val = 0
var sum = 0
if currentL1Node != nil {
l1Val = currentL1Node!.val
currentL1Node = currentL1Node!.next
}
if currentl2Node != nil {
l2Val = currentl2Node!.val
currentl2Node = currentl2Node!.next
}
sum = l1Val + l2Val + out
out = sum / 10
let resultNode = ListNode(sum % 10)
if currentResultNode == nil {
result = resultNode
currentResultNode = result
} else {
currentResultNode!.next = resultNode
currentResultNode = resultNode
}
}
return result
}
}
网友评论