Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
The solution is trivial. Just keep in mind to deal with every corner case. Find the new head first and then give each list a iterator to iterate all elements.
C++ Code:
/* * func: merge_sorted_list * goal: merget two sorted list to one list * @param l1: list 1 * @param l2: list 2 * return: new head of the merged list */ ListNode* merge_sorted_list(ListNode *l1, ListNode *l2){ if(!l1){ return l2; } if(!l2){ return l1; } ListNode *it1 = l1; ListNode *it2 = l2; ListNode *new_head = nullptr; //Set up new head if(it1->val >= it2->val){ new_head = it2; it2 = it2->next; }else{ new_head = it1; it1 = it1->next; } ListNode *it = new_head; while(it1 && it2){ if(it1->val <= it2->val){ it->next = it1; it1 = it1->next; it = it->next; }else{ it->next = it2; it2 = it2->next; it = it->next; } } if(it1){ it->next = it1; } if(it2){ it->next = it2; } return new_head; }
Python Code:
# func: merge two sorted list into one # @param l1: list 1 # @param l2: list 2 # @return: the head of the new list def merge_sorted_list(l1, l2): if not l1: return l2 if not l2: return l1 iter1 = l1 iter2 = l2 # Set up the new head node if l1.val <= l2.val: new_head = l1 iter1 = iter1.next else: new_head = l2 iter2 = iter2.next iter = new_head while iter1 and iter2: if iter1.val <= iter2.val: iter.next = iter1 iter1 = iter1.next iter = iter.next else: iter.next = iter2 iter2 = iter2.next iter = iter.next #Contatenate remaining part if iter1: iter.next = iter1 if iter2: iter.next = iter2 return new_head
No comments:
Post a Comment