## 1.中缀转后缀算法思想
遍历字符串:
一.若为数字1~9,进入后缀队列;
二.若为左括号‘(’,进入符号栈;
三.若为右括号’)‘,将栈顶元素压入后缀队列,直到栈顶为’(‘;
四.若为‘+’,‘-‘,当栈不为空时,将栈顶元素压入后缀队列,直到栈顶为’(‘;
五.若为’*‘,’\‘,当栈不为空且栈顶元素不为’+‘,’-‘时,将栈顶元素压入后缀队列,直到栈顶为’(‘。
遍历结束时,若栈不为空,将栈内元素压入后缀队列。
2.后缀表达式求值算法思想
遍历后缀表达式:
一.若为数字1~9,进入数据栈;
二.若为运算符:’+‘,’-‘,’*‘,’/‘,取出数据栈顶两个元素进行运算,结果压栈
三.输出栈顶元素。
运行代码
#include "stdafx.h"
#include<iostream>
using namespace std;
#include<stack>
#include<queue>
int transform_calculate(char* c);
int _tmain(int argc, _TCHAR* argv[])
{
char c1[]={"((1+2)*(3+4))"};
transform_calculate(c1);
char c2[]="(((1+2)*3-4)/5)";
transform_calculate(c2);
system("pause");
return 0;
}
int transform_calculate(char* c)
{
stack<char> s;
stack<int> s1;
queue<char> q;
cout<<"中缀表达式:";
for (int i = 0; i < strlen(c); i++)
{
cout<<c[i]<<" ";
}
cout<<endl;
for(int i=0;i<strlen(c);i++)
{
if(c[i]>'0'&&c[i]<='9')
q.push(c[i]);
else if(c[i]=='(')
s.push(c[i]);
else if(c[i]==')')
{
while(s.top()!='(')
{
q.push(s.top());
s.pop();
}
s.pop();
}
else if(c[i]=='+'||c[i]=='-')
{
while(s.top()!='(')
{
if(!s.empty())
{
q.push(s.top());
s.pop();
}
}
s.push(c[i]);
}
else if(c[i]=='*'||c[i]=='/')
{
while(s.top()!='('&&s.top()!='+'&&s.top()!='-')
{
if(!s.empty())
{
q.push(s.top());
s.pop();
}
}
s.push(c[i]);
}
}
while(!s.empty())
{
q.push(s.top());
s.pop();
}
cout<<"后缀表达式:";
queue<char> p=q;
while(!p.empty())
{
cout<<p.front()<<" ";
p.pop();
}
cout<<endl;
while(!q.empty())
{
if(q.front()>'0'&&q.front()<='9')
{
s1.push(q.front()-'0');
q.pop();
}
else if(q.front()=='+')
{
int i=s1.top();
s1.pop();
int j=s1.top();
s1.pop();
s1.push(j+i);
q.pop();
}
else if(q.front()=='-')
{
int i=s1.top();
s1.pop();
int j=s1.top();
s1.pop();
s1.push(j-i);
q.pop();
}
else if(q.front()=='*')
{
int i=s1.top();
s1.pop();
int j=s1.top();
s1.pop();
s1.push(j*i);
q.pop();
}
else if(q.front()=='/')
{
int i=s1.top();
s1.pop();
int j=s1.top();
s1.pop();
s1.push(j/i);
q.pop();
}
}
cout<<"计算结果:";
while(!s1.empty())
{
cout<<s1.top();
s1.pop();
}
cout<<endl<<endl;
return true;
}
运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200305091718919.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzY1NjMyNw==,size_16,color_FFFFFF,t_70)