From 6715c406163ec7b16c06e0b8c679531438f0abf8 Mon Sep 17 00:00:00 2001 From: sh0723 Date: Sat, 18 Jul 2026 13:53:01 +0900 Subject: [PATCH] =?UTF-8?q?circular=20queue=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../array/circular_queue/circular_queue.cpp | 346 ++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 src/data_structure_implement/array/circular_queue/circular_queue.cpp diff --git a/src/data_structure_implement/array/circular_queue/circular_queue.cpp b/src/data_structure_implement/array/circular_queue/circular_queue.cpp new file mode 100644 index 0000000..d34f0ef --- /dev/null +++ b/src/data_structure_implement/array/circular_queue/circular_queue.cpp @@ -0,0 +1,346 @@ +#include +#include +#include +using namespace std; +class CircularQueue { + public: + CircularQueue(); + ~CircularQueue(); + + void push(int value); + void pop(); + + int& front(); + int& back(); + + int size() const; + int capacity() const; + bool empty() const; + void clear(); + void reserve(int newCapacity); + + private: + int* data; + int front_index; + int rear_index; + int current_size; + int current_capacity; + +}; + +CircularQueue::CircularQueue(): data(nullptr),front_index(0), rear_index(0), current_size(0), current_capacity(0) {} + +CircularQueue::~CircularQueue() { + delete[] data; +} + +void CircularQueue::push(int value) { + if(current_size == current_capacity) { + reserve(current_capacity==0 ? 1 : current_capacity*2); + } + + data[rear_index] = value; + rear_index = (rear_index + 1) % current_capacity; + current_size++; +} + +void CircularQueue::pop() { + if (current_size == 0) return; + + front_index = (front_index + 1) % current_capacity; + current_size--; +} + + +int& CircularQueue::front() { + if(current_size == 0) { + throw out_of_range("quque is empty"); + } + + return data[front_index]; +} +int& CircularQueue::back() { + if(current_size == 0) { + throw out_of_range("quque is empty"); + } + + int back_index = (rear_index - 1 + current_capacity) % current_capacity; + return data[back_index]; +} + +int CircularQueue::size() const{ + return current_size; +} +int CircularQueue::capacity() const{ + return current_capacity; +} +bool CircularQueue::empty() const{ + return current_size == 0; +} +void CircularQueue::clear(){ + current_size = 0; + front_index = 0; + rear_index = 0; +} +void CircularQueue::reserve(int newCapacity){ + if (newCapacity <= current_capacity) { + return; + } + + int* newData = new int[newCapacity]; + for (int i=0; i