栈表达式求值程序

#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <stdlib.h>

typedef int Status;

#define STACK_INIT_SIZE 100  //初始分配量
#define STACKINCREMENT 10    //存储空间的分配增量

typedef char ElemType;    
typedef ElemType OperandType;   //操作数
typedef char OperatorType;

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

 

Status InitStack(SqStack &S)
{
 //构造一个空栈S
    S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if(!S.base) exit (OVERFLOW);
 S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
    return OK;
}

Status GetTop(SqStack S){
 ElemType e;
 if (S.top == S.base) return ERROR;
 e = *(S.top-1);
 return e;
}

Status Push (SqStack &S,ElemType e)
{
 //插入元素e为新的栈顶元素
 if (S.top - S.base >= S.stacksize){
  S.base = (ElemType *) realloc ( S.base,
   (S.stacksize + STACKINCREMENT) * sizeof(ElemType));
  if(!S.base) exit (OVERFLOW);
  S.top = S.base + S.stacksize;
  S.stacksize += STACKINCREMENT;
 }
 *S.top++ = e;
 return OK;
}

Status Pop (SqStack &S,ElemType &e){
 //若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
    if(S.top == S.base) return ERROR;
    e = * --S.top;
    return OK;
}

char In(char c,char OP[])
{
 if(c>=35 && c<=47)
  return 1;
 else return 0;
}

char OP[8]={'+','-','*','/','(',')','#','/0'};
int m[7][7]=

{1,1,2,2,2,1,1,
  1,1,2,2,2,1,1,   

 1,1,1,1,2,1,1,
    1,1,1,1,2,1,1,
    2,2,2,2,2,0,-1,
    1,1,1,1,-1,1,1,
    2,2,2,2,2,-1,0};

char Precede(char i,char j)
{
 int a,b; char *p;
 for(p=OP,a=0;*p!='/0';p++,a++)
  if(*p==i) break;
 for(p=OP,b=0;*p!='/0';p++,b++)
  if(*p==j) break;
  if(m[a][b]==1) return '>';
  else if(m[a][b]==2) return '<';
  else if(m[a][b]==0) return '=';
  else return 'O';
}

char Operate(char a,char theta,char b)
{
 if(a>47) a=atoi(&a);
 if(b>47) b=atoi(&b);
 switch(theta)
 {
 case '+': return a+b;
    break;
 case '-': return a-b;
   break;
 case '*': return a*b;
   break;
 case '/': return a/b;
   break;
 }
}

OperandType EvaluateExpression()
{
 SqStack OPTR,OPND;
 OperandType a,b,c; OperatorType theta;
 InitStack(OPTR); Push(OPTR,'#');
 InitStack(OPND); c=getchar();
 while (c!='#' || GetTop(OPTR)!='#')
 {
  if (!In(c,OP)){Push(OPND,c);c=getchar();}
  else
   switch(Precede(GetTop(OPTR),c))
  {
   case '<' :
    Push(OPTR,c); c = getchar();
    break;
   case '=' :
    Pop(OPTR,c); c = getchar();
    break;
   case '>' :
    Pop(OPTR,theta);
    Pop(OPND,b); Pop(OPND,a);
    Push(OPND,Operate(a,theta,b));
    break;
  }
 }
 return GetTop(OPND);
}

void main()
{
 printf("(以#为结束符)/n");
 printf("请输入:/n");
 int a;
 a=(int)EvaluateExpression();
 printf("%d",a);
 getch();
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值