-
-
Save reterVision/ab4755710acfa48e5d25 to your computer and use it in GitHub Desktop.
Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| class Queue | |
| { | |
| public: | |
| Queue(int size); | |
| ~Queue(); | |
| bool enqueue(int value); | |
| int dequeue(); | |
| bool is_full(); | |
| bool is_empty(); | |
| void print(); | |
| protected: | |
| int* container; | |
| int count; | |
| int size; | |
| }; | |
| Queue::Queue(int size) | |
| { | |
| this->container = new int[size]; | |
| this->size = size; | |
| this->count = 0; | |
| } | |
| Queue::~Queue() | |
| { | |
| if (this->container != NULL) | |
| delete this->container; | |
| this->container = NULL; | |
| } | |
| bool Queue::enqueue(int value) | |
| { | |
| if (this->is_full()) | |
| { | |
| cout << "Queue overflow!" << endl; | |
| return false; | |
| } | |
| this->container[this->count] = value; | |
| this->count++; | |
| return true; | |
| } | |
| int Queue::dequeue() | |
| { | |
| if (this->is_empty()) | |
| { | |
| cout << "Queue lower flow!" << endl; | |
| return -1; | |
| } | |
| int result = this->container[0]; | |
| // Move the rest of the elements | |
| for (int i=0; i<this->count; i++) | |
| this->container[i] = this->container[i+1]; | |
| this->count--; | |
| return result; | |
| } | |
| bool Queue::is_full() | |
| { | |
| return this->count == this->size; | |
| } | |
| bool Queue::is_empty() | |
| { | |
| return this->count == 0; | |
| } | |
| void Queue::print() | |
| { | |
| for (int i=0; i<count; i++) | |
| cout << this->container[i] << endl; | |
| } | |
| int main(int argc, char* argv[]) | |
| { | |
| Queue queue(10); | |
| queue.enqueue(1); | |
| queue.enqueue(2); | |
| queue.enqueue(3); | |
| queue.enqueue(4); | |
| queue.print(); | |
| cout << "Dequeue" << endl; | |
| queue.dequeue(); | |
| queue.print(); | |
| cout << "Dequeue" << endl; | |
| queue.dequeue(); | |
| queue.print(); | |
| cout << "Dequeue" << endl; | |
| queue.dequeue(); | |
| queue.print(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment