后缀表达式+栈(详解)(c++)
前言
很抱歉,上一期没有介绍栈stack的用法,今天简要介绍一下,再讲讲后缀表达式,用stack栈做一些后缀表达式的练习。
栈
栈stack是c++中系统给出的栈,有了它,就不用自己创建栈啦!
头文件
栈stack的头文件就是#include <stack>
创建
定义一个名叫a的字符串栈:stack<char> a;
定义一个名叫a的整数栈:stack<int> a;
以此类推
用法
在栈a的栈顶加入元素b:a.push(b)
删除栈a的栈顶元素:a.pop()
栈a的栈顶元素:a.top()
判断栈a是否为空:a.empty()
后缀表达式
我们做数学时,用的都是中缀表达式。
那么,什么是中缀表达式呢?
如:2+3,(5+6+7)/2......这些都是中缀表达式。
后缀表达式,就是在中缀表达式的基础上,将数字提前,把符号往后放。
如:
2+3的后缀表达式是2 3 +
(5+6+7)/2的后缀表达式是5 6 7 + + 2 /
而中缀表达式转成后缀表达式的规则是:
1.操作数直接输出
2.操作符入栈前,弹出栈中优先级更高或相等的运算符
3.左括号(入栈,右括号)弹出栈内元素直到(
4.操作符优先级 *和/大于+和-
那么,你学会了吗?
中缀转后缀
中缀表达式转后缀表达式的方法已经说过了,直接上代码:
#include <iostream>
#include <stack>using namespace std;int main()
{stack<char> a;int n = 0;string str;while(true){cin>>str[n];if(str[n]=='.') break;n++;}string b;string tmp;int lb = 0;int lt = n;for(int i = 0;i<n;i++){if(str[i]=='*'||str[i]=='/'){while(true){if(a.empty()==true) break;if(a.top()=='+'||a.top()=='-'||a.top()=='(') break;b[lb++] = a.top();a.pop();lt--;}a.push(str[i]);tmp[lt++] = str[i];}else if(str[i]=='+'||str[i]=='-'){while(true){if(a.empty()==true) break;if(a.top()=='(') break;b[lb++] = a.top();a.pop();lt--;a.push(str[i]);tmp[lt++] = str[i];}a.push(str[i]);}else if(str[i]=='('||str[i]==')'){if(str[i]=='('){a.push(str[i]);tmp[lt++] = str[i];}else if(str[i]==')'){while(true){if(a.empty()==true) break;if(a.top()=='(') break;b[lb++] = a.top();a.pop();lt--;}a.pop();lt--;}}else{b[lb++] = str[i];}}while(a.empty()!=true){b[lb++] = a.top();a.pop();}for(int i = 0;i<lb;i++){cout<<b[i]<<" ";}return 0;
}
后缀表达式求值
(输入以点为结束)
#include <iostream>
#include <stack>using namespace std;int main()
{stack<int> a;while(true){char ch;cin>>ch;if(ch=='.') break;if(ch>='0'&&ch<='9'){a.push((int)ch-48);}else if(ch!=' '){int aa = a.top();a.pop();int bb = a.top();a.pop();if(ch=='*') a.push(aa*bb);else if(ch=='/') a.push(bb/aa);else if(ch=='+') a.push(aa+bb);else if(ch=='-') a.push(bb-aa);}}cout<<a.top();return 0;
}