文章目录
1、栈(stack)的定义
栈(stack)是限定在表尾进行插入或删除操作的线性表。如图a,表尾称为栈顶,表头端称为栈底。栈修改的原则为:后进先出。
运用 stack, 必须声明请头文件: #include <stack>。
stack 声明:如声明一个元素类型为整型的 stack :stack<int> st;

2、栈(stack)的主要成员函数
(1)栈主要的三个成员函数
st.push() // 将一个元素置入stack 内。
st.top() //返回stack内的 “下一个” 元素。
st.pop() //从stack中移除栈顶元素
(2)注意
如果stack 内没有元素,则执行 top() 和 pop() 会导致未定义的行为。所以,在使用前可以先用成员函数 size() 或 empty() 来检验容器是否为空。
(3)用法示例
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> st;
//进栈
st.push(1);
st.push(2);
st.push(3);
//访问栈顶元素
cout << "(1)" << st.top() << endl;
//出栈
st.pop();
cout << "(2)" << st.top() << endl;
//输出元素个数
cout << "(3)" << st.size() << endl;
return 0;
}
3、栈(stack)的应用
(1)进制转换
题目描述
输入任意一个非负十进制整数 n,计算并输出与其等值的 x 进制数;
样例输入1
1348
8
样例输出1
2504
样例输入2
78
2
样例输出2
1001110
代码
#include <iostream>
#include <stack>
using namespace std;
int main(){
int n, x;
stack<int> s;
cin >> n >> x;
while(n){
s.push(n%x);
n = n/x;
}
while(!s.empty()){
int e = s.top();
s.pop();
cout << e;
}
return 0;
}
(2)括号匹配的检验
题目描述
假设表达式中允许包含三种括号:圆括号、方括号和花括号,其嵌套的顺序随意,即([]()) 或[([][])] 等为正确的格式, [(]) 或 ([()) 或 (()]) 均为不正确的格式。
输入
输入一串括号,以符号 ‘#’ 作为结束标志。
输出
若输入的括号格式正确,则输出 “匹配成功”;否则输出 “匹配失败”
样例输入
[([][])]#
样例输出
匹配成功
代码
#include <iostream>
#include <stack>
using namespace std;
int main(){
char ch;
stack<char> st;
cin >> ch;
while(ch != '#'){
if(ch == '(' || ch == '[' || ch == '{')
st.push(ch);
if(ch==')' && st.top()=='(' || ch==']' && st.top()=='[' || ch=='}' && st.top()=='{')
st.pop();
cin >> ch;
}
if(st.empty()) cout << "匹配成功" << endl;
else cout << "匹配失败" << endl;
return 0;
}
本文详细介绍了C++ STL中的栈(stack)数据结构,包括栈的定义、主要成员函数,以及如何在进制转换和括号匹配检验中应用。在进制转换中,通过栈实现从十进制到其他进制的转换;在括号匹配检验中,利用栈的特性判断括号的正确性。此外,还提到了栈在行编辑、迷宫求解和汉诺塔问题中的用途。
296

被折叠的 条评论
为什么被折叠?



