You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4]
Example 2:
Input: list1 = [], list2 = [] Output: []
Example 3:
Input: list1 = [], list2 = [0] Output: [0]
Constraints:
- The number of nodes in both lists is in the range [0, 50].
- -100 <= Node.val <= 100
- Both list1andlist2are sorted in non-decreasing order.
SOLUTION:- Time complexity:
- The function - mergeTwoListstakes two linked lists as input parameters:- list1and- list2. It returns the merged sorted linked list.
- The initial checks - if not list1:and- if not list2:handle the case where either- list1or- list2is empty. If one of the lists is empty, the function simply returns the other non-empty list. This is because merging an empty list with a non-empty list would result in the same non-empty list.
- The variables - headand- currentare declared and initialized.- headis a dummy node with a value of 0, and- currentis used to keep track of the current position in the merged list.
- The condition - while list1 and list2: Checks if both- list1and- list2are not empty. In a singly-linked list, an empty list is represented by- None, so this condition ensures that the loop continues as long as there are still nodes to process in both- list1and- list2. This loop iterates through the lists and merges the nodes based on their values.
- Inside the loop, the code compares the values at the current nodes of - list1and- list2. If the value of- list1.valis less than or equal to the value of- list2.val, the current node of- list1should come first in the merged list.- current.next = list1sets the- nextattribute of the- currentnode to- list1, effectively appending- list1to the merged list.
- list1 = list1.nextmoves the- list1pointer to the next node in- list1.
 
- If the value of - list2.valis less than the value of- list1.val, the current node of- list2should come first in the merged list. The process is similar to the above case but with- list2.
- After setting the - nextnode in the merged list,- currentis updated to- current.nextto move the pointer to the newly added node.
- Once either - list1or- list2becomes empty, the loop terminates.
- If there are remaining nodes in - list1, they are appended to the merged list by setting- current.next = list1.
- If there are remaining nodes in - list2, they are appended to the merged list by setting- current.next = list2.
- Finally, the head of the merged list (excluding the dummy node) is returned as - head.next.
Comments
Post a Comment