后缀表达式计算
用栈写的一个简单的后缀表达式求值。水平有限,没有考虑错误数据输入问题。而且只考虑除法得到整数值的情况(不能整除的话,我只能想到变量全改成double型来处理)希望各位能提出更好的方法和建议!!!
程序代码:#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct Stack
{
int data;
struct Stack * next;
}* stack;
stack push( stack st, int val );
stack pop( stack st );
int peep( stack st ); //得到栈顶元素
int isop( char ch ); //判断是否运算符
int main()
{
stack s = NULL;
int result,temp,first,second,i;
char str[20];
printf("输入后缀表达式(数字先用字母表示):");
scanf("%s",str);
for( i = 0; i < strlen(str); i++ )
{
if( !isop(str[i]) ) //对于非运算符,入栈
{
printf("输入%c的值:",str[i]);
scanf("%d",&temp);
s = push( s, temp );
}
else
{ //遇到运算符,获取栈中最上面两个元素,并计算,所得结果入栈
second = peep(s);
s = pop(s);
first = peep(s);
s = pop(s);
if( '+' == str[i] )
{
result = first + second;
}
else if( '-' == str[i] )
{
result = first - second;
}
else if( '*' == str[i] )
{
result = first * second;
}
else if( '/' == str[i] )
{
result = first/second;
}
s = push( s,result );
}
}
printf("结果是%d",peep(s));
return 0;
}
stack push( stack st, int val ) //头插法建立栈,新建结点next指向原来的首节点,成为新的首节点,并作为函数返回值
{
stack new_st = (stack)malloc(sizeof(struct Stack));
new_st->data = val;
new_st->next = st;
return new_st;
}
stack pop( stack st )
{
stack temp;
if( NULL == st )
{
printf("空栈");
return NULL;
}
else
{
temp = st->next;
free(st);
return temp;
}
}
int isop( char ch )
{
if( ch=='+' || ch=='-' || ch=='*' || ch=='/' )
return 1;
else
return 0;
}
int peep( stack st)
{
if( NULL == st )
{
printf("空栈");
return NULL;
}
else
{
return st->data;
}
}运行示例:输入后缀表达式(数字先用字母表示): ab+cd-/
输入a的值 80
输入b的值 20
输入c的值 5
输入d的值 1
结果是25


