Merging Two Linked Lists
Merging two linked lists means weaving their nodes together into a single ordered chain. The common technique is a two-pointer walk: look at both current heads, pick whichever is smaller, attach it to the result, and move that pointer forward.
This trick only pays off when both lists were already sorted going in — you end up with a fully sorted merged list without ever needing to run a separate sort afterward.
Tip: Merging is efficient when input lists are already sorted and doesn’t require extra space beyond a few pointers.
Steps to Merge
- Create a dummy node to act as the starting point of the merged list
- Use a pointer (current) to track the last node in the merged list
- While both lists are non-empty, compare the current nodes
- Attach the smaller node to the merged list and move that list's pointer forward
- Once one list is exhausted, link the remaining part of the other list to the merged list
- Return the node next to dummy as the head of the merged list
Edge Cases
- Both lists are empty
- One list is empty
- All nodes in one list are smaller than the other
- Lists have overlapping values
- Input lists are not sorted (may result in unsorted merged list)
Best Practices
- Ensure both input lists are sorted before merging
- Always use a dummy node to simplify edge case handling
- Track edge conditions where one list might be empty
- Avoid modifying original input lists if immutability is required
- Consider recursive merging for a concise approach (at the cost of stack space)
Advertisement