hello-algo/codes/cpp/chapter_stack_and_queue/array_stack.cpp

86 lines
1.6 KiB
C++
Raw Permalink Normal View History

/**
* File: array_stack.cpp
* Created Time: 2022-11-28
* Author: qualifier1024 (2539244001@qq.com)
*/
#include "../utils/common.hpp"
/* 基于数组实现的栈 */
class ArrayStack {
private:
2022-11-30 02:27:26 +08:00
vector<int> stack;
public:
/* 获取栈的长度 */
int size() {
2022-11-30 02:27:26 +08:00
return stack.size();
}
/* 判断栈是否为空 */
2023-09-14 03:36:31 +08:00
bool isEmpty() {
return stack.size() == 0;
}
/* 入栈 */
void push(int num) {
2022-11-30 02:27:26 +08:00
stack.push_back(num);
}
/* 出栈 */
2023-12-19 21:55:57 +08:00
int pop() {
int num = top();
2022-11-30 02:27:26 +08:00
stack.pop_back();
2023-12-19 21:55:57 +08:00
return num;
}
/* 访问栈顶元素 */
int top() {
2023-09-14 03:36:31 +08:00
if (isEmpty())
2022-12-20 14:13:21 +08:00
throw out_of_range("栈为空");
2022-11-30 02:27:26 +08:00
return stack.back();
}
/* 返回 Vector */
vector<int> toVector() {
2022-11-30 02:27:26 +08:00
return stack;
}
};
/* Driver Code */
int main() {
/* 初始化栈 */
ArrayStack *stack = new ArrayStack();
/* 元素入栈 */
stack->push(1);
stack->push(3);
stack->push(2);
stack->push(5);
stack->push(4);
cout << "栈 stack = ";
printVector(stack->toVector());
/* 访问栈顶元素 */
int top = stack->top();
cout << "栈顶元素 top = " << top << endl;
/* 元素出栈 */
2023-12-19 21:55:57 +08:00
top = stack->pop();
cout << "出栈元素 pop = " << top << ",出栈后 stack = ";
printVector(stack->toVector());
/* 获取栈的长度 */
int size = stack->size();
cout << "栈的长度 size = " << size << endl;
/* 判断是否为空 */
2023-09-14 03:36:31 +08:00
bool empty = stack->isEmpty();
cout << "栈是否为空 = " << empty << endl;
2023-01-14 19:52:11 +08:00
// 释放内存
delete stack;
return 0;
}