Skip to content

Commit

Permalink
Add scala solution for 21-Merge-Two-Sorted-Lists
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisKheng committed Sep 25, 2022
1 parent b5c0237 commit 918d008
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions scala/21-Merge-Two-Sorted-Lists.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def mergeTwoLists(list1: ListNode, list2: ListNode): ListNode = {
val head = new ListNode()
var tail = head
var (ptr1, ptr2) = (list1, list2)

while (ptr1 != null && ptr2 != null) {
if (ptr1.x <= ptr2.x) {
tail.next = ptr1
ptr1 = ptr1.next
} else {
tail.next = ptr2
ptr2 = ptr2.next
}

tail = tail.next
}

if (ptr1 != null) {
tail.next = ptr1
} else if (ptr2 != null) {
tail.next = ptr2
}

return head.next
}
}

0 comments on commit 918d008

Please sign in to comment.