Back to articles
Merging Two Sorted Linked Lists
How-ToDevOps

Merging Two Sorted Linked Lists

via Dev.to DevOpsAshiq Omar

In this task, I worked on merging two sorted linked lists into a single sorted linked list. This problem helped me understand how linked lists work and how to handle pointers efficiently. What I Did: I created a function mergeTwoLists that takes two sorted linked lists as input and merges them into one sorted list. Example: List1: 1 → 3 → 5 List2: 2 → 4 → 6 Output: 1 → 2 → 3 → 4 → 5 → 6 How I Solved It: To solve this problem, I used a dummy node technique to simplify handling the head of the new list. Step-by-step approach: I created a dummy node to act as the starting point of the merged list Used a pointer called tail to keep track of the last node in the merged list Compared nodes from both lists: If list1.val <= list2.val, I attached list1 node Otherwise, I attached list2 node Moved the pointer (tail) forward each time Continued this until one list becomes empty Final Step: If any nodes are left in either list, I attached them directly to the end Code: '''python class ListNode: def

Continue reading on Dev.to DevOps

Opens in a new tab

Read Full Article
7 views

Related Articles