-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort_a_k_sorted_DLL.cpp
More file actions
113 lines (90 loc) · 1.76 KB
/
Copy pathSort_a_k_sorted_DLL.cpp
File metadata and controls
113 lines (90 loc) · 1.76 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
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next, *prev;
};
void insert(struct Node** head, int data)
{
Node* temp = new Node;
temp->data = data;
temp->next = temp->prev = NULL;
if((*head) == NULL)
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
void printList(struct Node* head)
{
if(head == NULL)
return;
while(head != NULL)
{
cout<<head->data<<" ";
head = head->next;
}
}
struct compare
{
bool operator()(Node* p1 , Node* p2)
{
return p1->data > p2->data;
}
};
Node* sortKDLL(Node* head , int k)
{
if(head == NULL)
return head;
priority_queue <Node* , vector<Node*> , compare> pq;
Node* newHead = NULL , *last;
for(int i=0 ; head != NULL && i<=k ; i++)
{
pq.push(head);
head = head->next;
}
while(!pq.empty())
{
if(newHead == NULL)
{
newHead = pq.top();
newHead->prev = NULL;
last = newHead;
}
else
{
last->next = pq.top();
pq.top()->prev = last;
last = pq.top();
}
pq.pop();
if(head != NULL)
{
pq.push(head);
head = head->next;
}
}
last->next = NULL;
return newHead;
}
int main()
{
Node* head = NULL;
insert(&head, 8);
insert(&head, 56);
insert(&head, 12);
insert(&head, 2);
insert(&head, 6);
insert(&head, 3);
cout<<"Initially DLL is : ";
printList(head);
int k = 2;
Node *answer = sortKDLL(head , k);
cout<<"\n\nDLL after sorting is : ";
printList(answer);
return 0;
}