栈5-后缀表达式的求解
求解过程
8 3 1 - 5 * +
数字:进栈 [1,3,8]
符号: -
从栈中弹出右操作数 -1
从栈中弹出左操作数 3-1
根据符号进行运算 2
将运算结果压入栈中 [2,8]
遍历结束, 栈中唯一的数字作为计算结果
定义栈结构
typedef struct MYNUM{
LinkNode node;
int val;
} MyNum;
判断数字
int isNumber(char c){
return c>='0' && c<='9';
}
运算符号操作
int operatorOperate(char c,int rightNum, int leftNum){
if(c=='+') return leftNum+rightNum;
if(c=='-') return leftNum-rightNum;
if(c=='*') return leftNum*rightNum;
if(c=='/') return leftNum/rightNum;
}
测试
int main(){
char *str = "831-5*+";
char *p = str;
//创建栈
LinkStack *stack = Init_LinkStack();
//'\0'是字符的末尾
while(*p!='\0'){
if(isNumber(*p)){
MyNum *num = (MyNum*)malloc(sizeof(MyNum));
num->val = *p-'0';
Push_LinkStack(stack, (LinkNode*)num);
}else{
//弹出右操作数
int rightNum = ((MyNum*)Top_LinkStack(stack))->val;
Pop_LinkStack(stack);
//弹出左操作数
int leftNum = ((MyNum*)Top_LinkStack(stack))->val;
Pop_LinkStack(stack);
//结果进栈
MyNum *num = (MyNum*)malloc(sizeof(MyNum));
num->val = operatorOperate(*p, rightNum, leftNum);
Push_LinkStack(stack,(LinkNode*)num);
}
p++;
}
if(Size_LinkStack(stack)==1){
MyNum *num1 = (MyNum*)Top_LinkStack(stack);
cout << str << "的结果是:" << num1->val << endl;
Pop_LinkStack(stack);
}
//释放内存
FreeSpace_LinkStack(stack);
system("pause");
return 0;
}
标签:LinkStack,rightNum,求解,后缀,int,leftNum,MyNum,stack,表达式
From: https://www.cnblogs.com/HIK4RU44/p/18144353