栈应用 表达式求值

来源:互联网 发布:农村淘宝网店查询 编辑:程序博客网 时间:2024/04/28 21:21
#include<stdio.h>#include<stdlib.h>#define LENGTH 100//初始分配栈的长度#define ADD_LEN 10//栈长增量typedef struct//定义字符栈{int *base;int *top;int stacksize;}SqStack;void InitStack(SqStack &S);//初始化一个栈void Push(SqStack &S,int e);//e进入栈顶void Pop(SqStack &S,int &m);//栈顶元素出栈int GetTop(SqStack &S);//获得栈顶元素int In(int c,char arr[]);//判断c是否是在运算符数组中从而判定是否是运算符char Precede(char x,char y);//比较x,y的优先级int Operate(int a,int theta,int b);//将a,b进行theta运算void main(){SqStack OPTR,OPND;    char OP[8]={'+','-','*','/','(',')','#'};//初始化运算符数组int a,b,c,theta,n;printf("Please input the expression and use '#' to end up:\n");c=getchar();InitStack(OPTR);Push(OPTR,'#');InitStack(OPND);while(c!='#'||GetTop(OPTR)!='#'){if(!In(c,OP)){Push(OPND,c-48);c=getchar();while(c>=48){Pop(OPND,n);Push(OPND,n*10+c-48);c=getchar();}}elseswitch(Precede(GetTop(OPTR),c)){case'<':Push(OPTR,c);c=getchar();break;case'=':Pop(OPTR,n);c=getchar();break;case'>':Pop(OPTR,theta);Pop(OPND,b);Pop(OPND,a);Push(OPND,Operate(a,theta,b));break;}}printf("The value of the expression is:%d\n",GetTop(OPND));}void InitStack(SqStack &S){S.base=(int *)malloc(LENGTH*sizeof(int));if(!S.base){printf("Fail to create Stack!\n");return;}S.top=S.base;S.stacksize=LENGTH;}void Push(SqStack &S,int e){if(S.top-S.base>=S.stacksize)//考虑栈是否已满,如满,则从新分配空间{S.base=(int *)realloc(S.base,(S.stacksize+ADD_LEN)*sizeof(int));if(!S.base){printf("Fail to push!\n");return;}S.top=S.base+S.stacksize;S.stacksize+=ADD_LEN;}*S.top++=e;} void Pop(SqStack &S,int &m){if(S.top==S.base){printf("The stack is empty!\n");return;}m=*--S.top;}int GetTop(SqStack &S) {if(S.base==S.top){printf("The stack is empty!\n");return 0;}return *(S.top-1);}int In(int c,char arr[]){char *p;for(p=arr;*p;p++)if(*p==c)return 1;return 0;}char Precede(char x,char y){if(x=='+'||x=='-'){if(y=='+'||y=='-'||y==')'||y=='#')return '>';if(y=='*'||y=='/'||y=='(')return '<';}if(x=='*'||x=='/'){if(y=='+'||y=='-'||y==')'||y=='*'||y=='/'||y=='#')return '>';if(y=='(')return '<';}if(x=='('){if(y=='+'||y=='-'||y=='*'||y=='/'||y=='(')return '<';if(y==')')return '=';}if(x==')')return '>';if(x=='#'){if(y=='+'||y=='-'||y=='*'||y=='/'||y=='(')return '<';if(y=='#')return '=';}}int Operate(int a,int theta,int b){if(theta=='+')return a+b;if(theta=='-')return a-b;if(theta=='*')return a*b;if(theta=='/')return a/b;}

1 0
原创粉丝点击