Given the heads of two linked lists, list1 and list2, where each linked list has its elements sorted in non-decreasing order, merge them into a single sorted linked list and return the head of the merged linked list.
Input: list1 = head -> 2 -> 4 -> 7 -> 9, list2 = head -> 1 -> 2 -> 5 -> 6
Output: head -> 1 -> 2 -> 2 -> 4 -> 5 -> 6 ->7 -> 9
Explanation: head -> 1 -> 2 -> 2 -> 4 -> 5 -> 6 ->7 -> 9, the underlined nodes come from list2, the others come from list1.
Input: list1 = head -> 1 -> 2 -> 3 -> 4, list2 = head -> 5 -> 6 -> 10
Output: head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 10
Explanation: head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 10, the underlined nodes come from list2, the others come from list1.
Input: list1 = head -> 0 -> 2, list2 = head -> 1 -> 3 -> 5 -> 6
#include <bits/stdc++.h>
using namespace std;
// Definition of singly linked list
struct ListNode {
int val;
ListNode *next;
ListNode(int data1) {
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1) {
val = data1;
next = next1;
}
};
class Solution {
public:
// Function to merge two sorted linked lists
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
vector<int> arr;
ListNode* temp1 = list1;
ListNode* temp2 = list2;
// Add elements from list1 to the vector
while(temp1 != NULL){
arr.push_back(temp1->val);
// Move to the next node in list1
temp1 = temp1->next;
}
// Add elements from list2 to the vector
while(temp2 != NULL){
arr.push_back(temp2->val);
// Move to the next node in list2
temp2 = temp2->next;
}
// Sorting the vector in ascending order
sort(arr.begin(), arr.end());
// Sorted vector to linked list
ListNode* dummyNode = new ListNode(-1);
ListNode* temp = dummyNode;
for(int i = 0; i < arr.size(); i++){
temp->next = new ListNode(arr[i]);
temp = temp->next;
}
// Return the head of
// merged sorted linked list
return dummyNode->next;
}
};
// Function to print the linked list
void printLinkedList(ListNode* head) {
ListNode* temp = head;
while (temp != nullptr) {
// Print the data of the current node
cout << temp->val << " ";
// Move to the next node
temp = temp->next;
}
cout << endl;
}
int main() {
// Example Linked Lists
ListNode* list1 = new ListNode(1);
list1->next = new ListNode(3);
list1->next->next = new ListNode(5);
ListNode* list2 = new ListNode(2);
list2->next = new ListNode(4);
list2->next->next = new ListNode(6);
cout << "First sorted linked list: ";
printLinkedList(list1);
cout << "Second sorted linked list: ";
printLinkedList(list2);
Solution solution;
ListNode* mergedList = solution.mergeTwoLists(list1, list2);
cout << "Merged sorted linked list: ";
printLinkedList(mergedList);
return 0;
}
import java.util.*;
// Definition of singly linked list
class ListNode {
int val;
ListNode next;
ListNode(int data1) {
val = data1;
next = null;
}
ListNode(int data1, ListNode next1) {
val = data1;
next = next1;
}
}
class Solution {
// Function to merge two sorted linked lists
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ArrayList<Integer> arr = new ArrayList<>();
ListNode temp1 = list1;
ListNode temp2 = list2;
// Add elements from list1 to the vector
while (temp1 != null) {
arr.add(temp1.val);
// Move to the next node in list1
temp1 = temp1.next;
}
// Add elements from list2 to the vector
while (temp2 != null) {
arr.add(temp2.val);
// Move to the next node in list2
temp2 = temp2.next;
}
// Sorting the vector in ascending order
Collections.sort(arr);
// Sorted vector to linked list
ListNode dummyNode = new ListNode(-1);
ListNode temp = dummyNode;
for (int i = 0; i < arr.size(); i++) {
temp.next = new ListNode(arr.get(i));
temp = temp.next;
}
// Return the head of
// merged sorted linked list
return dummyNode.next;
}
}
// Function to print the linked list
public static void printLinkedList(ListNode head) {
ListNode temp = head;
while (temp != null) {
// Print the data of the current node
System.out.print(temp.val + " ");
// Move to the next node
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
// Example Linked Lists
ListNode list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(5);
ListNode list2 = new ListNode(2);
list2.next = new ListNode(4);
list2.next.next = new ListNode(6);
System.out.print("First sorted linked list: ");
printLinkedList(list1);
System.out.print("Second sorted linked list: ");
printLinkedList(list2);
Solution solution = new Solution();
ListNode mergedList = solution.mergeTwoLists(list1, list2);
System.out.print("Merged sorted linked list: ");
printLinkedList(mergedList);
}
# Definition of singly linked list
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Function to merge two sorted linked lists
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
arr = []
temp1 = list1
temp2 = list2
# Add elements from list1 to the vector
while temp1:
arr.append(temp1.val)
# Move to the next node in list1
temp1 = temp1.next
# Add elements from list2 to the vector
while temp2:
arr.append(temp2.val)
# Move to the next node in list2
temp2 = temp2.next
# Sorting the vector in ascending order
arr.sort()
# Sorted vector to linked list
dummyNode = ListNode(-1)
temp = dummyNode
for val in arr:
temp.next = ListNode(val)
temp = temp.next
# Return the head of
# merged sorted linked list
return dummyNode.next
# Function to print the linked list
def printLinkedList(head: ListNode):
temp = head
while temp:
# Print the data of the current node
print(temp.val, end=" ")
# Move to the next node
temp = temp.next
print()
if __name__ == "__main__":
# Example Linked Lists
list1 = ListNode(1)
list1.next = ListNode(3)
list1.next.next = ListNode(5)
list2 = ListNode(2)
list2.next = ListNode(4)
list2.next.next = ListNode(6)
print("First sorted linked list: ", end="")
printLinkedList(list1)
print("Second sorted linked list: ", end="")
printLinkedList(list2)
solution = Solution()
mergedList = solution.mergeTwoLists(list1, list2)
print("Merged sorted linked list: ", end="")
printLinkedList(mergedList)
// Definition of singly linked list
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
class Solution {
// Function to merge two sorted linked lists
mergeTwoLists(list1, list2) {
let arr = [];
let temp1 = list1;
let temp2 = list2;
// Add elements from list1 to the vector
while (temp1) {
arr.push(temp1.val);
// Move to the next node in list1
temp1 = temp1.next;
}
// Add elements from list2 to the vector
while (temp2) {
arr.push(temp2.val);
// Move to the next node in list2
temp2 = temp2.next;
}
// Sorting the vector in ascending order
arr.sort((a, b) => a - b);
// Sorted vector to linked list
let dummyNode = new ListNode(-1);
let temp = dummyNode;
for (let i = 0; i < arr.length; i++) {
temp.next = new ListNode(arr[i]);
temp = temp.next;
}
// Return the head of
// merged sorted linked list
return dummyNode.next;
}
}
// Function to print the linked list
function printLinkedList(head) {
let temp = head;
while (temp) {
// Print the data of the current node
process.stdout.write(temp.val + " ");
// Move to the next node
temp = temp.next;
}
console.log();
}
let list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(5);
let list2 = new ListNode(2);
list2.next = new ListNode(4);
list2.next.next = new ListNode(6);
console.log("First sorted linked list: ");
printLinkedList(list1);
console.log("Second sorted linked list: ");
printLinkedList(list2);
let solution = new Solution();
let mergedList = solution.mergeTwoLists(list1, list2);
console.log("Merged sorted linked list: ");
printLinkedList(mergedList);
Time Complexity: O(N1 + N2) + O(N log N) + O(N) where N1 is the number of linked list nodes in the first list, N2 is the number of linked list nodes in the second list, and N is the total number of nodes (N1 + N2). Traversing both lists into the array takes O(N1 + N2), sorting the array takes O((N1 + N2) X log(N1 + N2)), and then traversing the sorted array and creating a list gives us another O(N1 + N2).
Space Complexity: O(N) + O(N) where N is the total number of nodes from both lists (N1 + N2). O(N) to store all the nodes of both the lists in an external array and another O(N) to create a new combined list.
#include <bits/stdc++.h>
using namespace std;
// Definition of singly linked list
struct ListNode {
int val;
ListNode *next;
ListNode(int data1) {
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1) {
val = data1;
next = next1;
}
};
class Solution {
public:
// Function to merge two sorted linked lists
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
// Create a dummy node to serve as
// the head of the merged list
ListNode* dummyNode = new ListNode(-1);
ListNode* temp = dummyNode;
// Traverse both lists simultaneously
while (list1 != nullptr && list2 != nullptr) {
/*Compare elements of both lists
and link the smaller node
to the merged list*/
if (list1->val <= list2->val) {
temp->next = list1;
list1 = list1->next;
} else {
temp->next = list2;
list2 = list2->next;
}
// Move the temporary pointer
// to the next node
temp = temp->next;
}
/*If any list still
has remaining elements,
append them to the merged list*/
if (list1 != nullptr) {
temp->next = list1;
} else {
temp->next = list2;
}
// Return merged list
return dummyNode->next;
}
};
// Function to print the linked list
void printLinkedList(ListNode* head) {
ListNode* temp = head;
while (temp != nullptr) {
// Print the data of the current node
cout << temp->val << " ";
// Move to the next node
temp = temp->next;
}
cout << endl;
}
int main() {
// Example Linked Lists
ListNode* list1 = new ListNode(1);
list1->next = new ListNode(3);
list1->next->next = new ListNode(5);
ListNode* list2 = new ListNode(2);
list2->next = new ListNode(4);
list2->next->next = new ListNode(6);
cout << "First sorted linked list: ";
printLinkedList(list1);
cout << "Second sorted linked list: ";
printLinkedList(list2);
Solution solution;
ListNode* mergedList = solution.mergeTwoLists(list1, list2);
cout << "Merged sorted linked list: ";
printLinkedList(mergedList);
return 0;
}
import java.util.*;
// Definition of singly linked list
class ListNode {
int val;
ListNode next;
ListNode(int data1) {
val = data1;
next = null;
}
ListNode(int data1, ListNode next1) {
val = data1;
next = next1;
}
}
class Solution {
// Function to merge two sorted linked lists
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
// Create a dummy node to serve as
// the head of the merged list
ListNode dummyNode = new ListNode(-1);
ListNode temp = dummyNode;
// Traverse both lists simultaneously
while (list1 != null && list2 != null) {
/*Compare elements of both lists
and link the smaller node
to the merged list*/
if (list1.val <= list2.val) {
temp.next = list1;
list1 = list1.next;
} else {
temp.next = list2;
list2 = list2.next;
}
// Move the temporary pointer
// to the next node
temp = temp.next;
}
/*If any list still
has remaining elements,
append them to the merged list*/
if (list1 != null) {
temp.next = list1;
} else {
temp.next = list2;
}
// Return merged list
return dummyNode.next;
}
}
// Function to print the linked list
public static void printLinkedList(ListNode head) {
ListNode temp = head;
while (temp != null) {
// Print the data of the current node
System.out.print(temp.val + " ");
// Move to the next node
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
// Example Linked Lists
ListNode list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(5);
ListNode list2 = new ListNode(2);
list2.next = new ListNode(4);
list2.next.next = new ListNode(6);
System.out.print("First sorted linked list: ");
printLinkedList(list1);
System.out.print("Second sorted linked list: ");
printLinkedList(list2);
Solution solution = new Solution();
ListNode mergedList = solution.mergeTwoLists(list1, list2);
System.out.print("Merged sorted linked list: ");
printLinkedList(mergedList);
}
# Definition of singly linked list
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# Function to merge two sorted linked lists
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
# Create a dummy node to serve as
# the head of the merged list
dummyNode = ListNode(-1)
temp = dummyNode
# Traverse both lists simultaneously
while list1 is not None and list2 is not None:
'''Compare elements of both lists
and link the smaller node
to the merged list'''
if list1.val <= list2.val:
temp.next = list1
list1 = list1.next
else:
temp.next = list2
list2 = list2.next
# Move the temporary pointer
# to the next node
temp = temp.next
'''If any list still
has remaining elements,
append them to the merged list'''
if list1 is not None:
temp.next = list1
else:
temp.next = list2
# Return merged list
return dummyNode.next
# Function to print the linked list
def printLinkedList(head: ListNode):
temp = head
while temp is not None:
# Print the data of the current node
print(temp.val, end=" ")
# Move to the next node
temp = temp.next
print()
if __name__ == "__main__":
# Example Linked Lists
list1 = ListNode(1)
list1.next = ListNode(3)
list1.next.next = ListNode(5)
list2 = ListNode(2)
list2.next = ListNode(4)
list2.next.next = ListNode(6)
print("First sorted linked list: ", end="")
printLinkedList(list1)
print("Second sorted linked list: ", end="")
printLinkedList(list2)
solution = Solution()
mergedList = solution.mergeTwoLists(list1, list2)
print("Merged sorted linked list: ", end="")
printLinkedList(mergedList)
// Definition of singly linked list
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
class Solution {
// Function to merge two sorted linked lists
mergeTwoLists(list1, list2) {
// Create a dummy node to serve as
// the head of the merged list
let dummyNode = new ListNode(-1);
let temp = dummyNode;
// Traverse both lists simultaneously
while (list1 !== null && list2 !== null) {
/*Compare elements of both lists
and link the smaller node
to the merged list*/
if (list1.val <= list2.val) {
temp.next = list1;
list1 = list1.next;
} else {
temp.next = list2;
list2 = list2.next;
}
// Move the temporary pointer
// to the next node
temp = temp.next;
}
/*If any list still
has remaining elements,
append them to the merged list*/
if (list1 !== null) {
temp.next = list1;
} else {
temp.next = list2;
}
// Return merged list
return dummyNode.next;
}
}
// Function to print the linked list
function printLinkedList(head) {
let temp = head;
while (temp !== null) {
// Print the data of the current node
process.stdout.write(temp.val + " ");
// Move to the next node
temp = temp.next;
}
console.log();
}
// Example Linked Lists
let list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(5);
let list2 = new ListNode(2);
list2.next = new ListNode(4);
list2.next.next = new ListNode(6);
console.log("First sorted linked list: ");
printLinkedList(list1);
console.log("Second sorted linked list: ");
printLinkedList(list2);
let solution = new Solution();
let mergedList = solution.mergeTwoLists(list1, list2);
console.log("Merged sorted linked list: ");
printLinkedList(mergedList);
Q: Why do we use a dummy head node?
A: It simplifies handling edge cases (e.g., when the first node should come from list2 instead of list1).
Q: What if we had more than two lists to merge?
A: Use Min-Heap (O(k log n)) for merging k lists.
Q: How would this approach change for circular linked lists?
A: Find the tail and properly link the merged list back to it.
Q: What if we needed to merge lists in descending order?
A: Use the same approach but compare in reverse (> instead of <).