Here is an algorithm for merging two sorted linked lists in C++:
- Create a new dummy node for the merged list.
- Initialize a pointer,
curr
, to point to the dummy node. - Iterate through each element in both lists using two pointers,
l1
andl2
. - Compare the first elements of each list.
- If the element in list 1 is smaller, append it to the merged list and move the pointer for list 1 to the next element.
- If the element in list 2 is smaller, append it to the merged list and move the pointer for list 2 to the next element.
- Repeat steps 4-6 until one of the lists is exhausted.
- Append the remaining elements from the non-empty list to the merged list.
- Return the dummy node's next pointer, as it is the head of the merged list.
Alternatively, for recursive algorithm:
- Create a helper function for merging two sorted linked lists.
- In the helper function, check for the base case: if one of the lists is empty, return the remaining list.
- Compare the first elements of each list.
- If the element in list 1 is smaller, append it to the merged list and recursively call the helper function with the next element of list 1 and the entire list 2.
- If the element in list 2 is smaller, append it to the merged list and recursively call the helper function with the entire list 1 and the next element of list 2.
- Repeat steps 3-5 until the base case is reached.
- Return the head of the merged list.
Both of these algorithms will effectively merge two sorted linked lists in C++, with the iterative algorithm having a faster time complexity of O(n) and the recursive algorithm having a time complexity of O(n log n).