Last active
January 12, 2019 11:36
-
-
Save benapie/54de9745bcdf5428883e553eedb78032 to your computer and use it in GitHub Desktop.
Implementation of a queue data type using arrays in C++.
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
| #define MAX_SIZE 32 | |
| /** | |
| * Implementation of a queue data type using an array. | |
| */ | |
| class QueueWithArray { | |
| private: | |
| int data_array[MAX_SIZE] = {}; | |
| int size = 0; | |
| int front_index = 0; | |
| int rear_index = 0; | |
| public: | |
| QueueWithArray() = default; | |
| /** | |
| * Adds an element to the end of the queue. | |
| * @param data the data of the element to add. | |
| */ | |
| void QueueItem(int data) { | |
| if (size == MAX_SIZE) { | |
| std::cerr << "Stack full." << std::endl; | |
| return; | |
| } | |
| if (size == 0) { | |
| data_array[front_index] = data; | |
| } else { | |
| rear_index = (rear_index + 1) % MAX_SIZE; | |
| data_array[rear_index] = data; | |
| } | |
| size++; | |
| } | |
| /** | |
| * Removes the element at the front of the queue and remvoes it. | |
| * @return the element at the front of the queue. | |
| */ | |
| int Enqueue() { | |
| if (size == 0) { | |
| std::cerr << "Stack empty." << std::endl; | |
| return -1; | |
| } | |
| front_index = (front_index + 1) % MAX_SIZE; | |
| size--; | |
| } | |
| /** | |
| * Returns the front of the queue without removing the element. | |
| * @return the element at the front of the queue. | |
| */ | |
| int Front() { | |
| return data_array[front_index]; | |
| } | |
| /** | |
| * Checks whether the queue is empty. | |
| * @return whether the queue is empty. | |
| */ | |
| bool is_empty() { | |
| return size == 0; | |
| } | |
| /** | |
| * Returns the number of elements in the queue. | |
| * @return the size of the queue. | |
| */ | |
| int get_size() { | |
| return size; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment