-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLMergeTwoSorted.cpp
More file actions
73 lines (66 loc) · 1.43 KB
/
LLMergeTwoSorted.cpp
File metadata and controls
73 lines (66 loc) · 1.43 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
~Node()
{
int value = this->data;
// memory free
if (this->next != NULL)
{
delete next;
this->next = NULL;
}
cout << "Memory is free for node with data " << value << endl;
}
};
Node* solve(Node* first, Node* second){
if(first->next == NULL){
first->next = second;
return first;
}
Node* curr1 = first;
Node* next1 = curr1->next;
Node* curr2 = second;
Node* next2 = curr2->next;
while(next1 != NULL && curr2 != NULL){
if(curr2->data >= curr1->data && curr2->data <= next1->data){
curr1->next = curr2;
next2 = curr2->next;
curr2->next = next1;
curr1 = curr2;
curr2 = next2;
}
else{
curr1 = next1;
next1 = next1->next;
if(next1 == NULL){
curr1->next = curr2;
return first;
}
}
}
return first;
}
Node* merge(Node* &first, Node* &second){
if(first == NULL){
return second;
}
if(second == NULL){
return first;
}
if(first->data <= second->data){
return solve(first,second);
}
else{
return solve(second,first);
}
}