1 Star 0 Fork 0

TommyGONG / learninggit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
后缀表达式.cpp 2.15 KB
一键复制 编辑 原始数据 按行查看 历史
TommyGONG 提交于 2019-11-12 23:33 . 后缀表达式
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
char operation[5]={'+','-','*','/','^'};
char OpList[5][5]={
{'=','=','<','<','<'},
{'=','=','<','<','<'},
{'>','>','=','=','<'},
{'>','>','=','=','<'},
{'>','>','>','>','>'},
};//优先级表
int topn=0,topo=0;
char numstack[100];//数字栈
char opstack[100];//符号栈
char expression[200];//表达式数组
void push_num(char q)//数字入栈
{
numstack[topn]=q;
topn++;
}
char pop_num()//数字出栈
{
return numstack[topn--];
}
void push_op(char ch)//操作符入栈
{
topo++;
opstack[topo]=ch;
}
char pop_op()//操作符出栈
{
return opstack[topo--];
}
char compare(char x,char y)//比较x,y的优先级
{
int a,b;
for(int i=0;i<=8;i++)
{
if(operation[i]==x)
{
a=i;
break;
}
}
for(int i=0;i<=8;i++)
{
if(operation[i]==y)
{
b=i;
break;
}
}
return OpList[a][b];
}
int main()
{
int N;
scanf("%d",&N);
char *p;
while(N--)
{
int length=0;
char op;
topo=0;
topn=0;
scanf("%s",expression);
p=expression;
while(*p!='#')
{
if((*p>='A'&&*p<='Z')||(*p>='a'&&*p<='z'))//操作数入栈
{
push_num(*p);
length++;
}
else if(*p=='+'||*p=='-'||*p=='*'||*p=='/'||*p=='^')
{
while(1)
{
if(topo==0||opstack[topo]=='(')//栈空或栈顶为(
{
push_op(*p);
length++;
break;
}
else if(compare(*p,opstack[topo])=='>')//优先级比栈顶元素高
{
push_op(*p);
length++;
break;
}
else if((compare(*p,opstack[topo])=='<')||(compare(*p,opstack[topo])=='='))//优先级比栈顶元素低
{
op=pop_op();
push_num(op);
}
}
}
else if(*p=='(') push_op(*p);
else if(*p==')')
{
while(opstack[topo]!='(')
{
op=pop_op();
push_num(op);
}
if(opstack[topo]=='(')//丢弃(
{
op=pop_op();
}
}
p++;
}//从左向右扫描完毕
topn--;
while(topn>=0)
{
op=pop_num();
push_op(op);
}
while(topo>0)
{
printf("%c",opstack[topo]);
topo--;
}
printf("\n");
}
return 0;
}
1
https://gitee.com/tommygong08/bit1120180473.git
git@gitee.com:tommygong08/bit1120180473.git
tommygong08
bit1120180473
learninggit
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891