Problem Statement
You are given the heads of two sorted linked lists list1 and list2.
…
Return the head of the merged linked list.
Approach
- Create a new node.
next
of this node will be the head of the merged list. - Create a pointer
current
that keeps track of the last node in the merged list. - While both lists are not empty:
- Identify the smaller element between the two lists.
- Set current to this smaller element.
- Move it’s list pointer to the next element.
- Set current to it’s next element.
- If one of the lists is not empty, set the
next
of current to the remaining 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 mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
var one = list1
var two = list2
let result = ListNode()
var current = result
while one != nil && two != nil {
if one!.val < two!.val {
current.next = one
one = one!.next
} else {
current.next = two
two = two!.next
}
current = current.next!
}
if one != nil {
current.next = one
} else {
current.next = two
}
return result.next
}
}
Complexity
- Time complexity: \(O(n + m)\), where \(n\) and \(m\) are the number of elements in the two lists.
- Space complexity: \(O(1)\)