#include
#include
#include
#define MAXSIZE 20
typedef struct stack{
int data[MAXSIZE];
int top;
}SqStack;
/*1.初始化*/
bool InitSqStack(SqStack * S){
S->top = -1;
return true;
}
/**2.压栈 */
bool PushStack(SqStack * S,int x){
if(S->top == MAXSIZE - 1){
printf("栈满\n");
return false;
}
S->top++;
S->data[S->top] = x;
return true;
}
/**3.出栈 */
int PopStack(SqStack * S){
if(S->top == -1){
printf("栈空\n");
return 0;
}
int x = S->data[S->top];
S->top--;
return x;
}
/**4.判断运算符的优先级操作 */
int Priority(char u){
switch (u)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
/**5.运算操作 */
void PopPush(SqStack * Sdata,SqStack * Soper){
//将Sdata数字栈中的两个数据出栈
int x;
int y;
x = PopStack(Sdata);
y = PopStack(Sdata);
//将Soper运算符栈中的运算符出栈
char u;
u = PopStack(Soper);
//计算两数之和
int n;
switch (u)
{
case '+':
n = y+x;
break;
case '-':
n = y-x;
break;
case '*':
n = y*x;
break;
case '/':
n = y/x;
break;
}
PushStack(Sdata,n);
}
/**6.扫描输入的字符串,分情况不断的进行PopPush操作,得出最终结果 */
int count(char * str){
//创建数据栈与运算符栈
SqStack Sdata,Soper;
//初始化
InitSqStack(&Sdata);
InitSqStack(&Soper);
//对字符串进行遍历
while(*str != '\0'){
//遍历到的字符是数字
if(*str >= '0' && *str <= '9'){
int y = *str - '0';
str++;
//如果是多个数字呢
while(*str >= '0' && *str <= '9'){
y = y*10+(*str - '0');
str++;
}
PushStack(&Sdata,y);
}
//如果栈为空,或字符为(,或字符的优先级大于栈顶字符的优先级就将其放入字符栈
else if(Soper.top == -1 || *str == '(' || Priority(*str) > Priority(Soper.data[Soper.top])){
PushStack(&Soper,*str);
str++;
}
//如果字符为)并且字符栈的栈顶元素为( 就出将字符栈的栈顶元素出栈
else if(*str == ')' && Soper.data[Soper.top] == '('){
int ch;
ch = PopStack(&Soper);
str++;
}
//字符的优先级小于等于栈顶字符的优先级就将其出栈,并且数据栈的栈顶与其相邻的两个元素出栈计算
else{
PopPush(&Sdata,&Soper);
}
}
//字符串表达式扫描完毕,再次使用PopPush清空数据栈与运算符栈并计算
while(Soper.top > -1){
PopPush(&Sdata,&Soper);
}
int n = Sdata.data[Sdata.top];
return n;
}
int main(){
char c[50];
printf("请你输入表达式\n");
scanf("%s",c);
int n = count(c);
printf("结果为:%d",n);
}