Skip to content

Commit 18697e0

Browse files
committed
feat: Add solution for LeetCode problem 21
1 parent 5a8bb66 commit 18697e0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// 21. Merge Two Sorted Lists.swift
3+
// https://leetcode.com/problems/merge-two-sorted-lists/description/
4+
// Algorithm
5+
//
6+
// Created by 홍승현 on 2024/05/04.
7+
//
8+
9+
import Foundation
10+
11+
final class LeetCode21 {
12+
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
13+
let dummy: ListNode? = .init(0)
14+
var currentNode: ListNode? = dummy
15+
var l1 = list1
16+
var l2 = list2
17+
18+
while l1 != nil, l2 != nil {
19+
if l1!.val < l2!.val {
20+
currentNode?.next = l1
21+
l1 = l1?.next
22+
} else {
23+
currentNode?.next = l2
24+
l2 = l2?.next
25+
}
26+
27+
currentNode = currentNode?.next
28+
}
29+
30+
currentNode?.next = l1 ?? l2
31+
32+
return dummy?.next
33+
}
34+
}

0 commit comments

Comments
 (0)