前言
上一个提到了通过数组和链表来实现堆栈,这里我们通过C++中的stl来实现堆栈。毕竟我们在实际应用的时候几乎不会自己去封装stack这样的数据结构,都是使用已经提供好的。
代码
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int> s;
// 入栈
for(int i=0; i < 5; i++)
s.push(i);
// 获取尺寸
cout << "the size of stack " << s.size() << endl;
// 注意这里的pop只是删除栈顶元素,并不会有返回值
s.pop();
cout << "the size of stack " << s.size() << endl;
// 返回栈顶元素
printf("%d\n", s.top());
//遍历stack
while(!s.empty()) {
printf("%d ", s.top());
s.pop();
}
printf("\n");
return 0;
}