Update array_stack.cpp

Make `vec` a private member.
This commit is contained in:
Yudong Jin 2022-11-29 00:26:18 +08:00 committed by GitHub
parent f772e28acb
commit 56ef5a71cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,37 +8,43 @@
/* 基于数组实现的栈 */ /* 基于数组实现的栈 */
class ArrayStack { class ArrayStack {
public: private:
vector<int> vec; vector<int> vec;
public:
/* 获取栈的长度 */ /* 获取栈的长度 */
int size() { int size() {
return vec.size(); return vec.size();
} }
/* 判断栈是否为空 */ /* 判断栈是否为空 */
bool empty() { bool empty() {
return vec.empty(); return vec.empty();
} }
/* 入栈 */ /* 入栈 */
void push(int num) { void push(int num) {
vec.push_back(num); vec.push_back(num);
} }
/* 出栈 */ /* 出栈 */
int pop() { int pop() {
int oldTop = vec.back(); int oldTop = vec.back();
vec.pop_back(); vec.pop_back();
return oldTop; return oldTop;
} }
/* 访问栈顶元素 */ /* 访问栈顶元素 */
int top() { int top() {
return vec.back(); return vec.back();
} }
/* 返回 Vector */
vector<int> toVector() {
return vec;
}
}; };
/* Driver Code */ /* Driver Code */
int main() { int main() {
/* 初始化栈 */ /* 初始化栈 */
@ -51,7 +57,8 @@ int main() {
stack->push(5); stack->push(5);
stack->push(4); stack->push(4);
cout << "栈 stack = "; cout << "栈 stack = ";
PrintUtil::printVector(stack->vec); vector<int> vec = stack->toVector();
PrintUtil::printVector(vec);
/* 访问栈顶元素 */ /* 访问栈顶元素 */
int top = stack->top(); int top = stack->top();
@ -60,7 +67,8 @@ int main() {
/* 元素出栈 */ /* 元素出栈 */
int pop = stack->pop(); int pop = stack->pop();
cout << "出栈元素 pop = " << pop << ",出栈后 stack = "; cout << "出栈元素 pop = " << pop << ",出栈后 stack = ";
PrintUtil::printVector(stack->vec); vec = stack->toVector();
PrintUtil::printVector(vec);
/* 获取栈的长度 */ /* 获取栈的长度 */
int size = stack->size(); int size = stack->size();
@ -69,6 +77,6 @@ int main() {
/* 判断是否为空 */ /* 判断是否为空 */
bool empty = stack->empty(); bool empty = stack->empty();
cout << "栈是否为空 = " << empty << endl; cout << "栈是否为空 = " << empty << endl;
return 0; return 0;
} }