使用栈的原理,实现一个简单的表达式计算。
演示了:读取字符,判断运算优先级别,压栈,弹栈,计算等功能。 为了简化程序,注意如下几点:
1、用一个数据域类型为char的链表,来生成 树栈和符号栈,每次存入数据要从int转换为char,取出数据要从char转化为int,没有处理负数情况,因此计算过程中不要出现负数。
2、遇到二位数以上,需要设置标志位,判断读数情况,为了简化,没有做这样的处理,因此只能输入个位数计算。
#include<stdlib.h>
#include<stdio.h>
struct stacknode{
char data;
struct stacknode *next;
};
typedef struct stacknode *Node;
Node operatorStack;/*运算符栈*/
Node operand; /*运算数栈*/
/*运算符优先级判断*/
int Is_Operator(char e){
switch (e){
case '+':case '-': return 2;break;
case '*':case '/': return 1;break;
default :return 0 ;
}
}
/*压栈*/
void Push(Node top, char e){
Node newNode;
newNode=(Node)malloc(sizeof(struct stacknode));/*分配空间*/
if (!newNode) {
printf("\n容量满了!");
exit(0);
}/*if*/
else {
newNode->data=e;
newNode->next=top->next;/*建立新链接*/
top->next=newNode;
}
}
/*运算符优先级的判定*/
int Priority(char e){
switch (e){
case '+':case '-':return 1;break;
case '*':case '/':return 2;break;
default :return 0;
}
}
/*判断栈是否为空栈*/
int StackEmpty(Node top){
if (top->next==NULL)
return 1;
else return 0;
}
/*弹出栈顶元素*/
char Pop(Node stack){
char e;
Node pointer;
/*判断是否为空栈*/
if ( !StackEmpty(stack)){
pointer=stack->next;
e=pointer->data;
stack->next=pointer->next;
free(pointer);
return e;
} else {
printf("\n栈是空的!");
return 0;
}
}
//运算
int Calculate(Node operand,Node operatorStack){
int oper1=0; /*前操作数*/
int oper2=0; /*后操作数*/
char op; /*运算符*/
oper1=Pop(operand)-'0';
oper2=Pop(operand)-'0';
op=Pop(operatorStack);
switch (op){
case '+':return (oper2+oper1);break;
case '-':return (oper2-oper1);break;
case '*':return (oper2*oper1);break;
case '/':return (oper2/oper1);break;
}
}
main(){
int e;
char expression[30];
char evaluate;
int current=0; /*表达式得位置*/
char curop; /*当前的操作符*/
Node top;
operand=(Node)malloc(sizeof(struct stacknode));/*分配操作数栈*/
operand->next=NULL;
operatorStack=(Node)malloc(sizeof(struct stacknode));/*分配操作符栈*/
operatorStack->next=NULL;
printf("\n请输入需要计算的表达式:");
gets(expression);
do{
/*判断是否为运算数*/
if (!Is_Operator(expression[current]) ){
Push(operand,expression[current]); /*运算数直接进栈*/
current++;
}
else {
curop=expression[current]; /*待入栈的运算符*/
/*运算符栈空,不进行优先级比较直接进栈*/
if ( StackEmpty(operatorStack) ) {
Push(operatorStack,curop);
current++;
}else {
top=operatorStack->next; /*栈顶运算符*/
e=Priority(curop)-Priority(top->data); /*优先级比较*/
switch (e){
case 1:{/*优先级高*/
Push(operatorStack,curop); /*运算符进运算符栈*/
current++;break;
}
case 0:case -1:{
/*将计算结果入运算数栈,需要转换为字符形式*/
Push(operand,Calculate(operand,operatorStack)+'0');
break;
}
default : printf("\nerror!");
}
}
}
}while( expression[current]!='\0' && expression[current]!='\n');
/*运算符栈非空,进行计算直至为空*/
while(!StackEmpty(operatorStack) ) {
Push(operand,Calculate(operand,operatorStack)+'0');
}
evaluate=Pop(operand);/*取最终结果*/
printf("\n表达式 [ %s ] 的运算结果是:%d\n ",expression,evaluate-'0');
system("pause");
}/*main*/
运行的结果如下:
请输入需要计算的表达式:2+4*7-6+9/3-7
表达式 [ 2+4*7-6+9/3-7 ] 的运算结果是:20
请输入需要计算的表达式:3+5-6/2-4
表达式 [ 3+5-6/2-4 ] 的运算结果是:1
.