逆波兰式,有关栈的问题

/*有关逆波兰式的问题,也叫后缀表达式(将运算符写在操作数之后);例如:a+b的逆波兰式为a b +;下列程序是有关数字与数字相加的,将程序简单理解为,如果是数字,那么压入栈中,如果是运算符,那么出栈,将此前压入栈中的两个数取出栈并且相加,相加后再压入栈中,以此类推(按运算符的优先级!)*/

#include <stdio.h>

#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_INIT_SIZE 20
#define STACK_INCREMENT 10
#define MAXBUFFER 10
typedef double ElemType;
typedef double Status;

typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;

Status InitStack( SqStack *S )
{
S->base = ( ElemType *) malloc ( STACK_INIT_SIZE*sizeof( ElemType ) );
S->top = S->base ;
S->stacksize = STACK_INIT_SIZE;

return 0;
}

//插入元素e,即入栈
Status Push( SqStack *S , ElemType e )
{
if ( S->top - S->base >= S->stacksize ) //当前容量大于或等于最大容量
{
//追加栈的空间
S->base = ( ElemType *) realloc ( S->base, S->stacksize + STACK_INCREMENT*sizeof( ElemType ) );
if ( !S->base )
return -1;
S->top = S->base + S->stacksize ;
S->stacksize = S->stacksize + STACK_INCREMENT;

}
//开始赋值
*S->top = e;
S->top++;

return 0; //注意返回值为0,不是e
}

//弹出元素e,即出栈
Status Pop ( SqStack *S , ElemType *e )
{
//首先判断栈内是否为空
if ( S->top == S->base )
return -1 ;

--S->top ;
*e = *S->top ;

return *e; //注意返回值为e,不是0
}

int StackLen ( SqStack *S )
{
return ( S->top - S->base );
}

int main()
{
SqStack s;
double d,e;
char c;
char str[MAXBUFFER];
InitStack(&s);
int i=0;
printf("请按逆波兰表达式输入数据,运算符之间用空格符分开,以'#'作为结束符:\n");
scanf("%c",&c);
while(c!='#')
{
while(isdigit(c)||c=='.')
{
str[i++]=c;
str[i]='\0';
if(i>=10)
{
printf("出错,输入数据过大\n");
return -1;
}
scanf("%c",&c);
if(c==' ')
{
d=atof(str);
Push(&s,d);
i=0;
break;
}
}
}
while(c!='#')
{
switch(c)
{
case '+':
Pop(&s,&e);
Pop(&s,&d);
Push(&s,d+e);
break;
case '-':Pop(&s,&e);Pop(&s,&d);Push(&s,d-e);break;
case '*':Pop(&s,&e);Pop(&s,&d);Push(&s,d*e);break;
case '/':Pop(&s,&e);Pop(&s,&d);
if(e!=0)
Push(&s,d/e);
else
{

printf("出错,除数不能为0");
return -1;}
break;
}
scanf("%c",c);
}

Pop(&s,&d);
printf("最终结果:%f\n",d);
return 0;
}

 //由于时间匆忙,来不及设置格式,可能是复制的原因,见谅!

posted @ 2015-10-20 20:01  近水樓台  阅读(229)  评论(0编辑  收藏  举报
Fork me on GitHub
回到顶部