Merge two sorted linked lists

problem [https://leetcode.com/problems/merge-two-sorted-lists/ 21. Merge Two Sorted Lists].

Problem description
Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.


 * Example 1
 * Input: l1 = [1,2,4], l2 = [1,3,4]
 * Output: [1,1,2,3,4,4]


 * Example 2
 * Input: l1 = [], l2 = []
 * Output: []


 * Example 3
 * Input: l1 = [], l2 = [0]
 * Output: [0]


 * Constraints
 * The number of nodes in both lists is in the range.
 * Both  and   are sorted in non-decreasing order.
 * Both  and   are sorted in non-decreasing order.

Analysis
We can use two pointers  and   to traverse through each of the lists, starting the head of each.

For each iteration:
 * If  is null (has reached the end), then we pick , and make   progress by one step.
 * If  is null (has reached the end), then we pick , and make   progress by one step.
 * If both of them are not null, then we pick the pointer with the smaller value, and make that pointer progress by one step.

Stop until both pointer have become null (reached the end).

For merging, we can create a dummy head, and let the merge tail pointer progress from it. Each time the tail points to a node that we have already visited, so we can relocate the link safely without disrupting the pointers  and. There is no need to create new nodes – we are playing with the nodes in-place.

Time complexity
We go over each node in the two linked lists exactly once. So the time complexity is O(m + n), where m and n are the length of the two linked lists.

Space complexity

 * Stack:We only have used the dummy head, merge tail,  and  . Hence the space complexity on stack is O(1).


 * Heap:Only the dummy head needs to be allocated during the iteration. So the stack complexity on heap is O(1).


 * Total space complexity: O(1).