This repository has been archived by the owner on Oct 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathCreate Merge sort on doubly linked list.cpp
125 lines (114 loc) · 2.53 KB
/
Create Merge sort on doubly linked list.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
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
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next, *prev;
};
Node *split(Node *head);
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;
}
}
Node *mergeSort(Node *head)
{
if (!head || !head->next)
return head;
Node *second = split(head);
head = mergeSort(head);
second = mergeSort(second);
return merge(head,second);
}
void insert(Node **head, int data)
{
Node *temp = new Node();
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
void print(Node *head)
{
Node *temp = head;
cout<<"Forward Traversal using next poitner\n";
while (head)
{
cout << head->data << " ";
temp = head;
head = head->next;
}
cout << "\nBackward Traversal using prev pointer\n";
while (temp)
{
cout << temp->data << " ";
temp = temp->prev;
}
}
void swap(int *A, int *B)
{
int temp = *A;
*A = *B;
*B = temp;
}
Node *split(Node *head)
{
Node *fast = head,*slow = head;
while (fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
Node *temp = slow->next;
slow->next = NULL;
return temp;
}
int main(void)
{
Node *head = NULL;
insert(&head, 7);
insert(&head, 40);
insert(&head, 2);
insert(&head, 1);
insert(&head, 20);
insert(&head, 10);
head = mergeSort(head);
cout << "Linked List after sorting\n";
print(head);
return 0;
}
//Input format:
//Enter the values for the nodes of the doubly linked list.
//Output format:
//Merge sort on the doubly linked list.
//Sample Input Format:
//7,40,2,1,20,10
//Sample Output Format:
//Linked List after sorting
//Forward Traversal using next pointer
//1 2 7 10 20 40
//Backward Traversal using prev pointer
//40 20 10 7 2 1