Problem Statement
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 contains a single digit. Add the two numbers and return the sum as a linked list.
…
Approach
- Pointer
a
andb
are used to iterate over the linked listsl1
andl2
respectively. - A new linked list
result
is created to store the sum of the two linked lists. It is initialized with a dummy node, that will be discarded. - A
current
pointer is used to add new nodes to theresult
linked list. - A
temp
variable is used to store the carry value. - Iterate until
a
,b
andtemp
are not empty. - Calculate the sum of the current nodes of
a
andb
and the carry valuetemp
. - Add the last digit of the sum to the
result
linked list. - Update the
temp
value with the carry value. - Move the pointers
a
andb
to the next nodes. - Return the next node of the
result
linked list.
Solution in Swift
/**
* 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; }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var a = l1
var b = l2
let result = ListNode()
var current = result
var temp = 0
while a != nil || b != nil || temp != 0 {
temp = (a?.val ?? 0) + (b?.val ?? 0) + temp
current.next = ListNode(temp % 10)
current = current.next!
temp = temp / 10
a = a?.next
b = b?.next
}
return result.next
}
}
Complexity
Time complexity: \(O(n)\)
where \(n\) is the length of the longer linked list.
Space complexity: \(O(n)\)
where \(n\) is the length of the longer linked list.