Leetcode: Merge Two Sorted Lists
Leetcode: Merge Two Sorted Lists (Kotlin)
Introduction
Merge Two Sorted Lists is an easy LinkedList Question on Leetcode. I will walk through the steps I used to solve it. Merge Two Sorted Lists - LeetCode
Problem Statement
Examples
Constraints
Brainstorm
This problem seemed pretty straightforward when I first encountered it.
-
We can start with a ListNode called merged that will hold the final LinkedList.
-
We will then check each list to see which one has a smaller value.
-
Whichever one has a smaller value, we should set the next node of merged with a new ListNode of this same value.
-
We should then move that current node and merged node to their next nodes.
-
Once we get to the end of one list, there is a possibility that one of the lists still has values that need to be added to the merged list. Since the lists are already sorted, we can add the rest of the non-empty list.
One edge case I did not account for was how I should return the head of the merged list. A common pattern I found was to use a “dummy” node, where the next node points to the head.
Note: When using Kotlin and working on problems with node classes on Leetcode, they often use val as the variable name. val is a keyword in Kotlin, so we have to surround it with backticks. I believe you can change the variable name in the node class with no problems. Check the code below.
Solution
{% gist https://gist.github.com/cmcoffeedev/7d64c8dde2f517f16256c27fd2c5c296.js %}