From 6a1ac5d50c0d5691e988727ef5db099a5fdc8667 Mon Sep 17 00:00:00 2001 From: sh0723 Date: Sat, 18 Jul 2026 14:46:38 +0900 Subject: [PATCH] =?UTF-8?q?deque=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../array/deque/deque.cpp | 354 ++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 src/data_structure_implement/array/deque/deque.cpp diff --git a/src/data_structure_implement/array/deque/deque.cpp b/src/data_structure_implement/array/deque/deque.cpp new file mode 100644 index 0000000..0264d3c --- /dev/null +++ b/src/data_structure_implement/array/deque/deque.cpp @@ -0,0 +1,354 @@ +#include +#include +#include +using namespace std; + +class IntDeque { +public: + IntDeque(); + ~IntDeque(); + + void pushFront(int value); + void pushBack(int value); + + void popFront(); + void popBack(); + + 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; +}; + +IntDeque::IntDeque() : data(nullptr), front_index(0), rear_index(0), current_size(0), current_capacity(0){} +IntDeque::~IntDeque() { + delete[] data; +} + +void IntDeque::pushFront(int value) { + if (current_size == current_capacity) { + reserve(current_capacity==0 ? 1 : current_capacity*2); + } + + front_index = (front_index-1+current_capacity)%current_capacity; + data[front_index] = value; + current_size++; +} +void IntDeque::pushBack(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 IntDeque::popFront(){ + if (current_size == 0) return; + front_index = (front_index + 1) % current_capacity; + current_size--; +} +void IntDeque::popBack(){ + if (current_size == 0) return; + rear_index = (rear_index - 1 + current_capacity) % current_capacity; + current_size--; +} + +int& IntDeque::front(){ + if (current_size == 0) { + throw out_of_range("deque is empty"); + } + + return data[front_index]; +} +int& IntDeque::back(){ + if (current_size == 0) { + throw out_of_range("deque is empty"); + } + + int back_index = (rear_index - 1 + current_capacity) % current_capacity; + return data[back_index]; +} + +int IntDeque::size() const{ + return current_size; +} +int IntDeque::capacity() const{ + return current_capacity; +} + +bool IntDeque::empty() const{ + return current_size == 0; +} +void IntDeque::clear(){ + current_size = 0; + front_index = 0; + rear_index = 0; +} + +void IntDeque::reserve(int newCapacity){ + if (newCapacity < 0) { + throw invalid_argument("capacity cannot be negative"); + } + if (newCapacity <= current_capacity) return; + + int *newData = new int[newCapacity]; + for (int i=0; i