Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active September 15, 2019 23:59
Show Gist options
  • Save jakehawken/72ccf38b120b61ade7a685b227f7ef04 to your computer and use it in GitHub Desktop.
Save jakehawken/72ccf38b120b61ade7a685b227f7ef04 to your computer and use it in GitHub Desktop.
Leetcode #21: Algorithm for merging two sorted linked lists into one sorted linked list.
public class ListNode: CustomDebugStringConvertible {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public var debugDescription: String {
let nextString = next?.debugDescription ?? "<end>"
return "<\(val)> " + nextString
}
}
extension ListNode {
func sortedInsert(_ newNode: ListNode) {
newNode.next = nil
if newNode.val < val {
swapValuesWith(newNode)
insertAfter(newNode)
}
else if let next = next {
next.sortedInsert(newNode)
}
else {
next = newNode
}
}
private func swapValuesWith(_ otherNode: ListNode) {
let val1 = val
let val2 = otherNode.val
val = val2
otherNode.val = val1
}
private func insertAfter(_ new: ListNode) {
new.next = next
next = new
}
}
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if let l1 = l1, l2 == nil {
return l1
}
else if l1 == nil, let l2 = l2 {
return l2
}
guard let root1 = l1, let root2 = l2 else {
return nil
}
var currentMergingNode: ListNode? = root2
while let nodeToMerge = currentMergingNode {
currentMergingNode = currentMergingNode?.next
root1.sortedInsert(nodeToMerge)
}
return root1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment