From aa2008b326c4613bebc8be54e920bf4a994592de Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 12 Dec 2023 14:44:38 +0100 Subject: [PATCH] =?UTF-8?q?problems(swift):=20add=20=E2=80=9C21.=20Merge?= =?UTF-8?q?=20Two=20Sorted=20Lists=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- swift/merge-two-sorted-lists.swift | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 swift/merge-two-sorted-lists.swift diff --git a/swift/merge-two-sorted-lists.swift b/swift/merge-two-sorted-lists.swift new file mode 100644 index 0000000..708dfd6 --- /dev/null +++ b/swift/merge-two-sorted-lists.swift @@ -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 + } +}