-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathl61.cpp
More file actions
83 lines (82 loc) · 2.01 KB
/
l61.cpp
File metadata and controls
83 lines (82 loc) · 2.01 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
#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;
}
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 whether 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 top
int index = front[qn-1];
//front ko aage badhao khatam ho jate hai.
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<<"Dequeued element is "<<q.dequeue(1)<<endl;
cout<<"Dequeued element is "<<q.dequeue(1)<<endl;
cout<<"Dequeued element is "<<q.dequeue(1)<<endl;
cout<<"Dequeued element is "<<q.dequeue(1)<<endl;
cout<<"Dequeued element is "<<q.dequeue(1)<<endl;
return 0;
}