算法笔记--数据结构--栈
栈的应用
- 栈是一种后进先出数据结构
- 栈顶指针Top是始终指向栈的最上方元素的
- 当栈空时,栈顶指针为-1

栈的常见操作
- 获取元素个数(size)
- 判空(empty)
- 进栈(push)
- 出栈(pop)
- 取出栈顶元素(top)
在之前,学过了STL的stack容器,所以以上函数可以通过库调用
- 清空(clear)
但是STL中没有实现清空函数,所以如果需要实现栈的清空,可以用一个while循环反复pop出元素直到栈空
while(!st.empty()){
st.pop();
}
例题
[codeup 1918]简单计算器
题目描述
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入
30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0
样例输出
12178.21
思路
- 🅰步骤一:中缀表达式转换为后缀表达式
- 🅱步骤二:计算后缀表达式
#include<iostream>
#include<stack>
#include<string>
#include<cstdio>
#include<queue>
#include<map>
using namespace std;
struct node{
double num; // 操作数
char op; // 操作符
bool flag; // true表示操作数,false表示操作符
};
string str; // 输入的字符串
stack<node> st; // node类型的栈
queue<node> qu; // node类型的队列;
map<char, int> op; // 用于实现char到int的映射,便于计算
void change(){ // 将中缀表达式转换为后缀表达式
node temp; // 中间变量
for(int i = 0; i < str.length();){ // 对字符串进行遍历
if(str[i] >= '0' && str[i] <= '9'){
temp.flag = true; // 如果是操作数,则标记为true
temp.num = str[i++] - '0'; // 记录操作数的第一个数,如操作数为123 = ((0*10+1)*10+2)*10+3
while(i < str.length() && str[i] >= '0' && str[i] <= '9'){ // 更新操作数
temp.num = temp.num * 10 + (str[i] - '0');
i++;
}
qu.push(temp); // 送进后缀操作符队列中
}else{
temp.flag = false; // 如果是操作符,则记为false
// 只要操作符栈的元素比该操作符优先级高
// 就把操作符栈栈顶元素弹出到后缀表达式的队列中
while(!st.empty() && op[str[i]] <= op[st.top().op]){
qu.push(st.top());
st.pop();
}
temp.op = str[i];
st.push(temp); // 把该操作符压入操作符栈中
i++;
}
}
// 如果操作符栈中还有操作符,就把它弹出到后缀表达式队列中
while(!st.empty()){
qu.push(st.top());
st.pop();
}
}
double calculate(){ // 计算后缀表达式
double temp1, temp2;
node cur, temp;
while(!qu.empty()){ // 只要后缀队列非空
cur = qu.front(); // 队首
qu.pop(); // 出队
if(cur.flag == true) st.push(cur); // 如果是操作数,直接压入栈中
else{ // 如果是操作符,则弹出栈内两个数
temp2 = st.top().num; // 弹出第一个数
st.pop();
temp1 = st.top().num; // 弹出第二个数
st.pop();
temp.flag = true;
if(cur.op == '+') temp.num = temp1 + temp2; // 加法
else if(cur.op == '-') temp.num = temp1 - temp2; // 减法
else if(cur.op == '*') temp.num = temp1 * temp2; // 乘法
else temp.num = temp1 / temp2; // 除法
st.push(temp); // 把计算结果压入栈中
}
}
return st.top().num; // 栈顶元素就是后缀表达式的值
}
int main(){
op['+'] = op['-'] = 1; // 通过map来设定操作符优先级
op['*'] = op['/'] = 2;
while(getline(cin, str), str != "0"){
for(string::iterator it = str.end(); it != str.begin(); it--){
if(*it == ' ') str.erase(it); // 去除空格
}
while(!st.empty()) st.pop(); // 初始化栈
change();
printf("%.2f\n", calculate());
}
return 0;
}
Write by Gqq

浙公网安备 33010602011771号