-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge Sort on Doubly Linked List
51 lines (48 loc) · 1.04 KB
/
Merge Sort on Doubly Linked 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
48
49
50
51
/*
Structure of the node of the list is as
struct Node
{
int data;
struct Node *next, *prev;
Node (int x){
data = x;
next = prev = NULL;
}
}; */
// Function to merge two DLLs
Node* split(Node *head){
Node *fast=head,*slow=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
Node *tmp=slow->next;
slow->next=NULL;
return tmp;
}
Node *merge(Node *first,Node *second){
if(!first)
return second;
if(!second)
return first;
if(first->data<second->data){
first->next=merge(first->next,second);
first->next->prev=first;
first->prev=NULL;
return first;
}else{
second->next=merge(first,second->next);
second->next->prev=second;
second->prev=NULL;
return second;
}
}
struct Node *sortDoubly(struct Node *head)
{
if(!head || !head->next)
return head;
Node *second=split(head);
head=sortDoubly(head);
second=sortDoubly(second);
return merge(head,second);
}