📅  最后修改于: 2023-12-03 15:37:15.022000             🧑  作者: Mango
In this question, we are given two linked lists. We need to write a function that merges them and returns the combined linked list. The merged list should be in ascending order.
We are given two linked lists List1
and List2
. We need to write a function that merges them and returns the merged linked list. The merged list should contain all the elements of both List1
and List2
, and should be in ascending order.
We can solve this problem using a simple algorithm. We start by creating a new linked list called mergedList
. We then traverse both List1
and List2
simultaneously. At each step, we compare the current elements of both lists and add the smaller one to mergedList
. We repeat this process until we have traversed both lists completely.
Once we have merged both lists, we need to return the head of mergedList
. The final linked list will have all the elements of List1
and List2
, and will be in ascending order.
Node mergeLists(Node l1, Node l2) {
Node dummy = new Node(0);
Node curr = dummy;
while (l1 != null && l2 != null) {
if (l1.data <= l2.data) {
curr.next = l1;
l1 = l1.next;
} else {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
// add remaining elements
if (l1 != null) {
curr.next = l1;
}
if (l2 != null) {
curr.next = l2;
}
return dummy.next;
}
The algorithm has to traverse both linked lists, so the time complexity is O(n+m)
where n
and m
are the lengths of List1
and List2
respectively.
We are creating a new linked list mergedList
, which requires additional space. The space complexity is therefore O(n+m)
where n
and m
are the lengths of List1
and List2
respectively.
In this question, we have seen how to merge two linked lists. We created a new linked list mergedList
and traversed both List1
and List2
simultaneously. At each step, we compared the current elements of both lists and added the smaller one to mergedList
. We returned the head of mergedList
, which contained all the elements of List1
and List2
in ascending order.