#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(); } } else switch(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; }
原文地址:http://blog.csdn.net/lucienduan/article/details/38333189