🧵 Merging Two Sorted Linked Lists in Kotlin: From Trial-and-Error to Clean Elegance
tl;dr: Code that works is good. Code that reads like a story is better.
💡 Why I Picked This Problem
I’ve been solving problems on LeetCode lately to sharpen my Kotlin and data structure skills. When I came across “Merge Two Sorted Lists”, I thought: Easy. Just compare and connect, right?
Well… not quite.
What looked simple on the surface turned into a mini journey of learning how to:
- Use dummy nodes
- Handle linked list edge cases
- Write idiomatic Kotlin
- And most importantly, go from working code to elegant code
This blog captures that journey.
🛠️ The Problem
You’re given two sorted singly linked lists. Merge them into one sorted list and return it. The result should reuse the nodes from the original lists — no creating new nodes.
❌ My First Attempt (Functional but Flawed)
At first glance, this feels like it should work… until you test it.
❗ What Went Wrong:
-
I was overwriting result.next on every iteration — never building a full list.
-
I forgot to track the tail of the result list.
-
I tried to compare val properties safely, but added unnecessary checks.
-
My final result.next = l1?.next ?: l2?.next skipped nodes!
This wasn’t just a logic fail — it was a reminder that linked lists don’t forgive sloppy thinking.
🔁 Refactoring and Debugging
I went back to the drawing board and broke it into smaller pieces:
✅ Use a dummy node to simplify list-building
✅ Use a tail pointer to track where we’re adding next
✅ Use safe Kotlin null-checking with ?:
✅ Replace manual pointer updates with Kotlin’s also
That led to something much more elegant.
✅ The Final Clean Kotlin Version
🧠 What I Love About This Version
✅ Uses Kotlin’s also to update references cleanly
✅ Safe handling of null pointers
✅ Dummy node pattern makes it easier to return the result
✅ tail clearly communicates intent — appending to the end of the list
✅ The loop reads naturally — like you’re telling Kotlin what to do in plain English
This version passes all test cases and feels solid, simple, and elegant — a big leap from where I started.
💬 Key Takeaways
-
Don’t rush linked list problems — edge cases matter more than you think.
-
Kotlin gives you powerful tools to write safe and readable code — use them.
-
Start with “does it work” — but always push toward “does it feel clean”
-
The also block trick is totally underrated.
🔭 What’s Next?
I’m considering a follow-up where I:
- Write a recursive version of this function in Kotlin
- Generalize this logic to merge k sorted lists
- Build a Kotlin-style unit test suite to validate edge cases
📢 Final Thoughts
There’s something deeply satisfying about taking messy, trial-and-error code and shaping it into something that’s both correct and beautiful. This little problem — just merging two lists — reminded me that code can be art when you care enough to polish it.
Thanks for reading!