给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class FMLeetcode_02: NSObject {
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
let retNode:ListNode = ListNode.init(0)
var first:ListNode? = l1
var second:ListNode? = l2
var jinwei:ListNode?
var nextNode:ListNode? = retNode
while first != nil || second != nil || jinwei != nil{
let left:Int = first == nil ? 0 : first!.val
let right:Int = second == nil ? 0 : second!.val
let jinweiCount:Int = jinwei == nil ? 0 : jinwei!.val
let count:Int = left + right + jinweiCount
let newNode = ListNode.init(count % 10)
nextNode?.next = newNode
let jinweiNumber:Int = count / 10
jinwei = jinweiNumber == 0 ? nil : ListNode.init(jinweiNumber)
first = first?.next == nil ? nil : first!.next
second = second?.next == nil ? nil : second!.next
nextNode = nextNode?.next
}
return retNode.next
}
}
需要注意的是:
1、要处理好初始传入nil的问题;
2、如果往后next的过程中出现nil了计算的时候要用0填充;
3、计算到最后的时候如果出现进位,就需要再次循环一次;