Created
October 4, 2020 04:22
-
-
Save TokisakiKurumi2001/31f7d3f72e083d0f49fabf2a7196039d to your computer and use it in GitHub Desktop.
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; | |
| template <class T> | |
| class AQueue { | |
| private: | |
| int front; | |
| int rear; | |
| int maxSize; | |
| int size; | |
| T * arr; | |
| public: | |
| AQueue(int size = 10) { | |
| this->maxSize = size; | |
| this->size = 0; | |
| this->front = this->rear = 0; | |
| arr = new T[maxSize]; | |
| } | |
| ~AQueue() { | |
| delete[] arr; | |
| } | |
| void enqueue(const T & element) { | |
| if (size < maxSize) { | |
| if (rear == maxSize) { | |
| rear = 0; | |
| arr[rear] = element; | |
| } | |
| else { | |
| arr[rear] = element; | |
| rear += 1; | |
| } | |
| size += 1; | |
| } | |
| else { | |
| cout << "Queue is full\n"; | |
| throw out_of_range("Queue is full\n"); | |
| } | |
| } | |
| T & dequeue() { | |
| if (size == 0) { | |
| cout << "Queue is empty\n"; | |
| throw out_of_range("Queue is empty\n"); | |
| } | |
| else { | |
| static T returnData; | |
| returnData = arr[front]; | |
| front += 1; | |
| if (front == maxSize) { | |
| front = 0; | |
| } | |
| size -= 1; | |
| return returnData; | |
| } | |
| } | |
| T & top() const { | |
| if (size == 0) { | |
| cout << "Queue is empty\n"; | |
| throw out_of_range("Queue is empty\n"); | |
| } | |
| else { | |
| static T returnData; | |
| returnData = arr[front]; | |
| return returnData; | |
| } | |
| } | |
| bool isEmpty() { | |
| return size == 0; | |
| } | |
| bool isFull() { | |
| return size == maxSize; | |
| } | |
| void printQueue() { | |
| if (rear >= front) { | |
| int i = 0; | |
| for (i = front; i < rear; i++) { | |
| cout << arr[i] << " "; | |
| } | |
| } | |
| else { | |
| int i = 0; | |
| for (i = front; i < maxSize - 1; i++) { | |
| cout << arr[i] << " "; | |
| } | |
| for (i = 0; i <= rear; i++) { | |
| cout << arr[i] << " "; | |
| } | |
| } | |
| } | |
| void debug() { | |
| cout << "Rear: " << front; | |
| } | |
| }; | |
| int main(int argc, char const * argv[]) | |
| { | |
| AQueue<int> * queue = new AQueue<int>(10); | |
| int i = 0; | |
| for (i = 0; i < 10; i++) { | |
| queue->enqueue(i); | |
| } | |
| queue->dequeue(); | |
| queue->enqueue(10); | |
| queue->printQueue(); | |
| cout << "\n"; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment