Merge Two Sorted Lists
Problem
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.
Solution Approach
Click - to see solution code
- C++
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if (list1 == NULL) return list2;
if (list2 == NULL) return list1;
if (list1->val > list2->val) swap(list1, list2);
ListNode* head;
head = (ListNode*)malloc(sizeof(ListNode*));
head = list1;
while (list1->next != NULL && list2 != NULL) {
if (list1->next->val <= list2->val) {
list1 = list1->next;
continue;
}
ListNode* temp;
temp = (ListNode*)malloc(sizeof(ListNode*));
temp = list2;
list2 = list2->next;
temp->next = list1->next;
list1->next = temp;
list1 = list1->next;
}
if (list2 != NULL) {
list1->next = list2;
}
return head;
}
};