-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay-066.cpp
106 lines (84 loc) · 2.21 KB
/
Day-066.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
#include<iostream>
using namespace std;
class kQueue {
public:
int n;
int k;
int *front;
int *rear;
int *arr;
int freeSpot;
int *next;
public:
kQueue(int n, int k) {
this -> n = n;
this -> k = k;
front = new int[k];
rear = new int[k];
for(int i=0; i<k; i++) {
front[i] = -1;
rear[i] = -1;
}
next = new int[n];
for(int i=0; i<n; i++) {
next[i] = i+1;
}
next[n-1] = -1;
arr = new int[n];
freeSpot = 0;
}
void enqueue(int data, int qn) {
//overflow
if( freeSpot == -1) {
cout << "No Empty space is present" << endl;
return;
}
//find first free index
int index = freeSpot;
//update freespot
freeSpot = next[index];
//check whther first element
if(front[qn-1] == -1){
front[qn-1] = index;
}
else{
//link new element to the prev element
next[rear[qn-1]] = index;
}
//update next
next[index] = -1;
//update rear
rear[qn-1] = index;
//push element
arr[index] = data;
}
int dequeue(int qn) {
//underflow
if(front[qn-1] == -1)
{
cout << "Queue UnderFlow " << endl;
return -1;
}
//find index to pop
int index = front[qn-1];
//front ko aage badhao
front[qn-1] = next[index];
//freeSlots ko manage karo
next[index] = freeSpot;
freeSpot = index;
return arr[index];
}
};
int main() {
kQueue q(10, 3);
q.enqueue(10, 1);
q.enqueue(15,1);
q.enqueue(20, 2);
q.enqueue(25,1);
cout << q.dequeue(1) << endl;
cout << q.dequeue(2) << endl;
cout << q.dequeue(1) << endl;
cout << q.dequeue(1) << endl;
cout << q.dequeue(1) << endl;
return 0;
}