problems(swift): add “21. Merge Two Sorted Lists”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
58a84ebb43
commit
aa2008b326
1 changed files with 42 additions and 0 deletions
42
swift/merge-two-sorted-lists.swift
Normal file
42
swift/merge-two-sorted-lists.swift
Normal file
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* 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 list1 = list1
|
||||
var list2 = list2
|
||||
|
||||
let head = ListNode()
|
||||
|
||||
var node: ListNode? = head
|
||||
while list1 != nil && list2 != nil {
|
||||
if list1!.val < list2!.val {
|
||||
node!.next = list1
|
||||
node = node!.next
|
||||
|
||||
list1 = list1!.next
|
||||
} else {
|
||||
node!.next = list2
|
||||
node = node!.next
|
||||
|
||||
list2 = list2!.next
|
||||
}
|
||||
}
|
||||
|
||||
if list1 != nil {
|
||||
node!.next = list1
|
||||
}
|
||||
if list2 != nil {
|
||||
node!.next = list2
|
||||
}
|
||||
|
||||
return head.next
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue