forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
08.01.2024.cpp
82 lines (67 loc) · 1.6 KB
/
08.01.2024.cpp
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
/*
The structure of linked list is the following
struct Node
{
int data;
Node* next;
};
*/
class Solution
{
public:
Node* merge(Node* node1, Node* node2){
if(node1->data > node2->data){
return merge(node2, node1);
}
Node* head = node1;
node1=node1->next;
Node* temp=head;
while(node1 && node2){
if(node1->data <=node2->data){
temp=temp->next;
node1=node1->next;
}
else{
temp->next=node2;
temp=temp->next;
node2 = node2->next;
temp->next = node1;
}
}
if(node2){
temp->next=node2;
}
return head;
}
Node* reverse(Node* node){
Node* temp=node;
Node* prev=NULL;
Node* next=temp->next;
while(next){
temp->next = prev;
prev=temp;
temp=next;
next=next->next;
}
temp->next =prev;
return temp;
}
struct Node * mergeResult(Node *node1,Node *node2)
{
// your code goes here
if(node1==NULL && node2==NULL){
return NULL;
}
if(node1==NULL){
return reverse(node2);
}
if(node2==NULL){
return reverse(node1);
}
//merge the linked list
Node* head = merge(node1, node2);
//reverse the linked list
head= reverse(head);
return head;
}
};