|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 诺诺诺诺诺诺诺 于 2017-10-27 13:30 编辑
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef double ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
InitStack(sqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if( !s->base )
exit(0);
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
Push(sqStack *s, ElemType e)
{
if( s->top - s->base >= s->stackSize )
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if( !s->base )
exit(0);
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
}
Pop(sqStack *s, ElemType *e)
{
if( s->top == s->base )
return;
*e = *--(s->top);
}
OpMember(sqStack s, char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
return 1;
else
return 0;
}
Operate(sqStack *s, double a, char ch, double b)
{
switch( ch )
{
case '+':
Push(&s, a+b);
break;
case '-':
Push(&s, a-b);
break;
case '*':
Push(&s, a*b);
break;
case '/':
if( b != 0 )
{
Push(&s, a/b);
}
else
{
printf("\n出错:除数为零!\n");
return -1;
}
break;
}
}
int main()
{
sqStack s;
char ch;
double a, b, result;
printf("输入后缀表达式,以#作为结束标志: \n");
scanf("%c", &ch);
InitStack( &s );
while(ch != "#")
{
if(!OpMember(s, ch))
Push(&s, ch);
else
{
Pop(&s, &b);
Pop(&s, &a);
Push(&s, Operate(&s, a, ch, b));
}
scanf("%c", &ch);
}
Pop(&s, &result);
printf("result = %f\n", result);
return 0;
}
|
|