satcking算法代码
时间: 2024-04-29 20:21:40 浏览: 33
下面是一个基本的堆栈(stack)类实现,包括 push、pop、top、size 和 empty 函数:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Stack {
private:
vector<int> data;
public:
// 将一个元素压入栈中
void push(int val) {
data.push_back(val);
}
// 从栈中弹出一个元素
void pop() {
if (!isEmpty()) {
data.pop_back();
}
}
// 返回栈顶元素的值
int top() {
return data.back();
}
// 返回栈中元素的个数
int size() {
return data.size();
}
// 判断栈是否为空
bool isEmpty() {
return data.empty();
}
};
```
使用堆栈类的示例:
```c++
int main() {
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << s.top() << endl; // 输出 3
s.pop();
cout << s.top() << endl; // 输出 2
cout << s.size() << endl; // 输出 2
cout << s.isEmpty() << endl; // 输出 false
return 0;
}
```