Skip to content

Instantly share code, notes, and snippets.

@Parassharmaa
Last active October 5, 2016 02:56
Show Gist options
  • Save Parassharmaa/3cfd8c61600c359c7f30c5888c212c5d to your computer and use it in GitHub Desktop.
Save Parassharmaa/3cfd8c61600c359c7f30c5888c212c5d to your computer and use it in GitHub Desktop.
Queue implementation via dynamic array.
#include <iostream>
using namespace std;
class queue {
int *arr;
int f,r, max;
public:
queue(int n) {
max = n;
arr = new int[max];
f=-1;r=-1;
}
void enqueue(int n);
void dequeue();
void peek();
};
int main() {
queue q(10);
q.enqueue(2);
q.enqueue(23);
q.enqueue(42);
q.dequeue();
q.enqueue(12);
q.peek();
return 0;
}
void queue::enqueue(int n) {
if(r==max-1 && f==0) {
cout<<"Overflow"<<endl;
}
else {
if(r==max) {
for (int i=0;i<r-f;i++) {
arr[i] = arr[f+i];
}
r-=f;
}
if(f==-1) {
f=0;
}
r+=1;
arr[r] = n;
}
}
void queue::dequeue() {
if(f==-1) {
cout<<"Underflow"<<endl;
}
else {
f+=1;
if(f>r) {
f = -1;
r = -1;
}
}
}
void queue::peek() {
if(f==-1 && r==-1) {
cout<<"list is empty"<<endl;
}
else {
for (int i=f;i<=r;i++) {
cout<<arr[i]<<" ";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment