forked from Masked-coder11/gfg-POTD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
15.03.2024.cpp
80 lines (64 loc) · 1.75 KB
/
15.03.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
class Solution
{
public:
Node* merge(Node *head1, Node* head2){
if (!head1) return head2; // base cases
if (!head2) return head1; // base cases
Node *temp = NULL;
if (head1->data < head2->data)
{
temp = head1; // picking the lower value
head1->next = mergelist(head1->next, head2);
// recursively merging the remaining list
}
else
{
temp = head2; // picking the lower value
head2->next = mergelist(head1, head2->next);
// recursively merging the remaining list
}
return temp;
}
void reverse(Node *&head){
Node* prev=NULL, *curr=head, *next;
while(curr){
next=curr->next;
curr->next= prev;
prev = curr;
curr=next;
}
head=prev;
}
void splitList(Node*head, Node **Ahead, Node**Dhead){
*Ahead=new Node(0);
*Dhead=new Node(0);
Node*ascn= *Ahead;
Node*dscn= *Dhead;
Node* curr=head;
while(curr){
ascn->next=curr;
ascn=ascn->next;
curr=curr->next;
if(curr){
dscn->next=curr;
dscn=dscn->next;
curr=curr->next;
}
}
ascn->next=NULL;
dscn->next=NULL;
*Ahead=(*Ahead)->next;
*Dhead=(*Dhead)->next;
return;
}
// your task is to complete this function
void sort(Node **head)
{
// Code here
Node*Ahead, *Dhead;
splitList(*head, &Ahead, &Dhead);
reverse(Dhead);
*head=merge(Ahead, Dhead);
return;
}
};