You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* 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? {
if l1 == nil && l2 == nil {
return nil
}
var g1 = l1
var g2 = l2
let result = ListNode(0)
var g3 = result
var move = false
var carry = false
while g1 != nil && g2 != nil {
if move {
g3.next = ListNode(0)
g3 = g3.next!
} else {
move = true
}
carry = setNodeAndReturnCarry(g3, val: g1!.val + g2!.val, carry: carry)
g1 = g1!.next
g2 = g2!.next
}
if g1 != nil {
while g1 != nil {
if move {
g3.next = ListNode(0)
g3 = g3.next!
} else {
move = true
}
carry = setNodeAndReturnCarry(g3, val: g1!.val, carry: carry)
g1 = g1!.next
}
} else {
while g2 != nil {
if move {
g3.next = ListNode(0)
g3 = g3.next!
} else {
move = true
}
carry = setNodeAndReturnCarry(g3, val: g2!.val, carry: carry)
g2 = g2!.next
}
}
if carry {
g3.next = ListNode(1)
}
return result
}
func setNodeAndReturnCarry(g: ListNode, val: Int, carry: Bool) -> Bool {
g.val = val
var tmpCarry = carry
if tmpCarry {
g.val += 1
}
if g.val >= 10 {
g.val = g.val%10
tmpCarry = true
} else {
tmpCarry = false
}
return tmpCarry
}
}