-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge two sorted list
47 lines (37 loc) · 973 Bytes
/
Merge two sorted list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <bits/stdc++.h>
/************************************************************
Following is the linked list node structure.
template <typename T>
class Node {
public:
T data;
Node* next;
Node(T data) {
next = NULL;
this->data = data;
}
~Node() {
if (next != NULL) {
delete next;
}
}
};
************************************************************/
Node<int>* sortTwoLists(Node<int>* first, Node<int>* second)
{
// Write your code here.
if(first == NULL)
return second;
if(second == NULL)
return first;
Node<int>* mergeHead;
if(first->data < second->data){
mergeHead = first;
mergeHead->next = sortTwoLists(first->next, second);
}
else{
mergeHead = second;
mergeHead->next = sortTwoLists(first, second->next);
}
return mergeHead;
}