Swift solution - Stack


  • 0
    class Solution {
        func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            var stack1 = [Int]()
            var stack2 = [Int]()
            var l1 = l1
            var l2 = l2
            var sum = 0
            var cur = ListNode(0)
            
            while l1 != nil {
                stack1.append(l1!.val)
                l1 = l1?.next
            }
            while l2 != nil {
                stack2.append(l2!.val)
                l2 = l2?.next
            }
            while !stack1.isEmpty || !stack2.isEmpty {
                if !stack1.isEmpty {
                    sum += stack1.removeLast()
                }
                if !stack2.isEmpty {
                    sum += stack2.removeLast()
                }
                cur.val = sum % 10
                let head = ListNode(sum / 10)
                head.next = cur
                cur = head
                sum /= 10
            }
            
            return cur.val == 0 ? cur.next : cur
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.