Merging Two Linked Lists
Merging two linked lists involves combining the nodes of both lists into one sorted list. This is typically done using a two-pointer approach where we repeatedly compare the heads of both lists and append the smaller node to the result.
This operation is especially useful when both input lists are already sorted. The result is also a sorted list without requiring additional sorting operations.
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)