问题描述
栈作为一种基本的数据结构,在一些算法中十分实用,本文利用C++库stack实现队列操作,包括:
- push():向栈内压入一个元素
- pop():从栈顶弹出一个元素(不返回任何值)
- empty():如果栈为空返回true,否则返回false
- top():返回栈顶元素,但不删除
- size():返回栈内元素个数
小伙伴们需要自取,有帮助的话可以点个赞~
注:本文中提供的代码均为完整代码,放入C++工程后可直接运行。
代码实现
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int>stk;
for (int i = 0; i < 50; i++)
{
stk.push(i);
}
cout << "栈的大小: " << stk.size() << endl;
cout << stk.top() << endl;
while(!stk.empty())
{
stk.pop();
}
cout << "栈的大小: " << stk.size() << endl;
system("pause");
return 0;
}