-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_two_sorted.cpp
More file actions
144 lines (102 loc) · 1.98 KB
/
Copy pathmerge_two_sorted.cpp
File metadata and controls
144 lines (102 loc) · 1.98 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "essentials.cpp"
void reverse_ll(struct node**head){
if(*head==NULL){
return;
}
else{
struct node*current=*head;
struct node*next=NULL;
struct node*prev=NULL;
while(current){
next =current->next;
current->next=prev;
prev=current;
current=next;
}
*head=prev;
}
}
struct node* sorted_merge(struct node*head1, struct node*head2)
{
struct node*head3=NULL;
if(head1==NULL && head2==NULL){
return NULL;
}
else if( head1 && !head2){
return head1;
}
else if(!head1 && head2){
return head2;
}
else{
if(head1->data<=head2->data){
head3=head1;
head1->next=sorted_merge(head1->next,head2);
}
else{
head3=head2;
head2->next=sorted_merge(head2->next,head1);
}
return head3;
}
}
struct node*sorted_merge1(struct node*head1, struct node*head2){
struct node*head3=NULL;
if(!head1 && !head2)
{
return NULL;
}
else if(!head1 && head2){
return head2;
}
else if(!head2 && head1){
return head1;
}
else{
struct node*temp1=head1;
struct node*temp2=head2;
// struct node*temp3=head3;
while(temp1 && temp2)
{
if(temp1->data<=temp2->data){
head3=push_atend(head3,temp1->data);
temp1=temp1->next;
}
else{
head3=push_atend(head3,temp2->data);
temp2=temp2->next;
}
}
while(temp1){
head3=push_atend(head3,temp1->data);
temp1=temp1->next;
}
while(temp2){
head3=push_atend(head3,temp2->data);
temp2=temp2->next;
}
return head3;
}
}
int main(){
struct node*head=NULL;
head=push_atend(head,5);
head=push_atend(head,10);
head=push_atend(head,15);
head=push_atend(head,40);
struct node*head1=NULL;
head1=push_atend(head1,2);
head1=push_atend(head1,3);
head1=push_atend(head1,20);
print_single_ll(head);
cout<<"\n";
print_single_ll(head1);
cout<<"\n";
// reverse_ll(&head);
struct node*finalhead=NULL;
finalhead=sorted_merge1(head,head1);
cout<<"\n";
// print_single_ll(finalhead);
reverse_ll(&finalhead);
print_single_ll(finalhead);
}