LeetCode #2 Add Two Numbers

LeetCode #2 Add Two Numbers

Question

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Solution

Approach #1

/**
 * 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 sum = 0
        let head = ListNode(0)
        var node: ListNode? = head
        var p = l1
        var q = l2
        while p != nil || q != nil {
            if let pVal = p?.val {
                sum += pVal
                p = p?.next
            }
            if let qVal = q?.val {
                sum += qVal
                q = q?.next
            }
            node?.next = ListNode(sum % 10)
            node = node?.next
            sum /= 10
        }
        if sum > 0 { node?.next = ListNode(sum) }
        return head.next
    }
}

Assume that m and n represents the length of l1 and l2 respectively.

Time complexity: O(max(m, n)).

Space complexity: O(max(m, n)).

转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/6848514.html

原文地址:https://www.cnblogs.com/silence-cnblogs/p/6848514.html