标签:
//表达式求值的实现
#include <cstdio>
#include <cstdlib>
//#define _OJ_
#define maxsize 100
typedef struct stack
{
int top;
int base;
char *elem;
} stack, *stack1;
stack1
creat_stack(void)
{
stack1 s;
s = (stack1) malloc (sizeof(stack));
s->elem = (char*) malloc (maxsize * sizeof(char));
s->top = s->base = 0;
//printf("s->elem == %p\n", s->elem);
return s;
}
void
push(stack1 s,char ch)
{
//printf("push == %c\n",ch);
s->elem[s->top++] = ch;
}
char
pop(stack1 s)
{
--s->top;
return s->elem[s->top];
//printf("pop == %c\n",s->elem[s->top]);
}
char
gettop(stack1 s)
{
return s->elem[s->top - 1];
}
char
oper(char a, char b, char op)
{
char s;
//printf("a== %c\n", a);
//printf("b== %c\n", b);
a = a - 48;
b = b - 48;
if(op == ‘+‘) s = a + b;
if(op == ‘-‘) s = a - b;
if(op == ‘*‘) s = a * b;
if(op == ‘/‘) s = a / b;
s = s + 48;
return s;
}
int
pre_op(char ch)
{
int i;
char a[7] = {‘+‘,‘-‘,‘*‘,‘/‘,‘(‘,‘)‘,‘\n‘,};
for(i = 0;i < 7;i++)
{
if(ch == a[i]) return i;
}
}
int main(int argc, char const *argv[]) {
#ifndef _OJ_ //ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif
unsigned char prior[7][7] =
{ // 运算符优先级表
// ‘+‘ ‘-‘ ‘*‘ ‘/‘ ‘(‘ ‘)‘ ‘#‘
/*‘+‘*/‘>‘, ‘>‘, ‘<‘, ‘<‘, ‘<‘, ‘>‘, ‘>‘,
/*‘-‘*/‘>‘, ‘>‘, ‘<‘, ‘<‘, ‘<‘, ‘>‘, ‘>‘,
/*‘*‘*/‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘<‘, ‘>‘, ‘>‘,
/*‘/‘*/‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘<‘, ‘>‘, ‘>‘,
/*‘(‘*/‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘=‘, ‘ ‘,
/*‘)‘*/‘>‘, ‘>‘, ‘>‘, ‘>‘, ‘ ‘, ‘>‘, ‘>‘,
/*‘#‘*/‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘<‘, ‘ ‘, ‘=‘,
};
int a, b;
char ch, ch1;
stack1 optr;
stack1 opnd;//printf("%p %p\n", optr, opnd);printf("%p %p\n", optr->elem, opnd->elem);
optr = creat_stack(); push(optr,‘\n‘);
opnd = creat_stack();
//printf("%d %d\n", optr->top, opnd->top);
ch = getchar();
while(ch != EOF){
while(ch != ‘\n‘ || gettop(optr) != ‘\n‘)
{
//printf("ch == %c\n", ch);
//printf("ch == %c\n", gettop(optr));
//printf("fdfdsfds");
if(‘0‘ <= ch && ch <= ‘9‘ ) {push(opnd,ch); ch = getchar();}
else{
switch(prior[pre_op(gettop(optr))][pre_op(ch)])
{
case ‘<‘ :
push(optr,ch); ch = getchar(); break;
case ‘=‘ :
pop(optr); ch = getchar(); break;
case ‘>‘ :
/*ch1 = gettop(optr);*/ ch1 = pop(optr);
/*a = gettop(opnd);*/ a = pop(opnd);
/*b = gettop(opnd);*/ b = pop(opnd);
push(opnd,oper(b,a,ch1)); break;
}
//printf("gettop == %c\n", gettop(optr));
}
}
printf("%c\n", gettop(opnd));
ch = getchar();
if(ch == ‘0‘) break;
}
return 0;
}
/*3+2+1
3-2-1
1+2*3
0
样例输出
6
0
7*/
标签:
原文地址:http://www.cnblogs.com/airfand/p/4941153.html