Created
January 8, 2020 02:53
-
-
Save spurscho/f0fb868498c57def5176e96669ebbf66 to your computer and use it in GitHub Desktop.
21. Merge Two Sorted Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { | |
var l1 = l1 | |
var l2 = l2 | |
var arr: [Int] = [] | |
while l1 != nil { | |
arr.append(l1?.val ?? -1) | |
l1 = l1?.next | |
} | |
while l2 != nil { | |
arr.append(l2?.val ?? -1) | |
l2 = l2?.next | |
} | |
guard arr.isEmpty != true else { | |
return nil | |
} | |
arr = arr.sorted() | |
var resNode: ListNode? = ListNode(arr[0]) | |
var currentNode = resNode | |
for idx in 1 ..< arr.count { | |
currentNode?.next = ListNode(arr[idx]) | |
currentNode = currentNode?.next | |
} | |
return resNode | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment