Skip to content

circular queue added #236

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Contributors.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,4 @@
* [Muskan](https://github.com/Muskan-goyal6)
* [Tarannum](https://github.com/giTan7)
* [HCamberos](https://github.com/HCamberos)
* [Igor](https://github.com/IgorBizyanov)
121 changes: 121 additions & 0 deletions Queue/queue.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
#include <iostream>
#include <stdlib.h>

using namespace std;

template <typename T>
class CircularQueue {
public:

CircularQueue(int k) {
size = k;
buffer = (T*)malloc(sizeof(T)*k);
head = -1;
tail = -1;
}

/*
This function inserts an element into CircularQueue
Args:
- int value: value to be inserted
*/
bool enQueue(T value) {
if (isFull()){

return false;
}
cout << "DEBUG size == 0 or Full" << endl;

if (isEmpty()) {
head = 0;
tail = 0;
}

else
tail = (tail + 1) % size;

buffer[tail] = value;
return true;
}

/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty())
return false;

buffer[head] = 0;
if (head == tail) {
head = tail = -1;
}
else
head = (head + 1) % size;

return true;
}

/** Get the front item from the queue. */
T Head() {
return buffer[head];
}

/** Get the last item from the queue. */
T Tail() {
return buffer[tail];
}


void print() {

for (int i = 0; i < size; ++i) {
cout << buffer[i] << " ";
}
cout << endl;
cout << "head = " << head << " tail = " << tail << endl;
}

private:

T *buffer;
int size;
int head;
int tail;

bool isEmpty() {
return (head == -1 && tail == -1);
}

bool isFull() {
return size == 0 || head == ((tail+1) % size);
}

};

/*Usage:
en x : enqueue x number to the end of our queue
de : dequeue head number

*/
int main() {
string command;
double key;
CircularQueue <double>qu = CircularQueue<double>(6);

while (true) {

cin >> command;
if (command == "en") {
cin >> key;
qu.enQueue(key);
qu.print();
}
if (command == "de") {
qu.deQueue();
qu.print();
}

if (command == "exit")
break;
}

return 0;
}