栈
栈是一种先进先出的数据结构,用处很大
进栈
使用push()函数进栈
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> a;
a.push(10);
a.push(100);
a.push(1000);
a.push(10000);
while(!a.empty()) {
cout << a.top() << " ";
a.pop();
}
return 0;
}
出栈
使用pop()函数出栈
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> a;
a.push(10);
a.push(100);
a.push(1000);
a.push(10000);
while(!a.empty()) {
cout << a.top() << " ";
a.pop();
}
return 0;
}
输出结果是
10000 1000 100 10
其他
- 使用top()函数访问栈顶
- 使用empty()函数判断栈是否为空
- 使用size()函数得到栈元素的数量
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> a;
a.push(10);
a.push(100);
a.push(1000);
a.push(10000);
cout << a.size();
cout << "\n";
while(!a.empty()) {
cout << a.top() << " ";
a.pop();
}
return 0;
}
??正文结束??