From 599f7b970a6a8708e19b90bda6e282e6c90c16fd Mon Sep 17 00:00:00 2001 From: sh0723 Date: Sat, 18 Jul 2026 12:47:20 +0900 Subject: [PATCH] =?UTF-8?q?stack=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../array/stack/implement_stack.cpp | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 src/data_structure_implement/array/stack/implement_stack.cpp diff --git a/src/data_structure_implement/array/stack/implement_stack.cpp b/src/data_structure_implement/array/stack/implement_stack.cpp new file mode 100644 index 0000000..43ee1e2 --- /dev/null +++ b/src/data_structure_implement/array/stack/implement_stack.cpp @@ -0,0 +1,174 @@ +#include +using namespace std; +class IntStack { +public: + IntStack(); + ~IntStack(); + void push(int num); + void pop(); + + int& top(); + int size() const; + int capacity() const; + + bool empty() const; + void clear(); + void reserve(int new_capacity); +private: + int *data; + int curr_capacity; + int curr_size; +}; + +IntStack::IntStack() : data(nullptr), curr_size(0), curr_capacity(0){} + +IntStack::~IntStack() { + delete[] data; +} + +void IntStack::push(int num) { + if (curr_capacity == curr_size) { + if (curr_capacity == 0) { + reserve(1); + } else { + reserve(curr_capacity * 2); + } + } + + data[curr_size] = num; + curr_size++; +} + +void IntStack::pop() { + if (curr_size == 0) return; + + curr_size--; +} + +int& IntStack::top() { + if (curr_size == 0) { + throw out_of_range("stack is empty"); + } + + return data[curr_size-1]; +} + +int IntStack::size() const{ + return curr_size; +} + +int IntStack::capacity() const{ + return curr_capacity; +} + +bool IntStack::empty() const{ + return curr_size == 0; +} + +void IntStack::clear() { + curr_size = 0; +} + +void IntStack::reserve(int new_capacity) { + if (new_capacity <= curr_capacity) return; + + int *new_data = new int[new_capacity]; + + for (int i=0; i