#include "stdafx.h"
#include "stack.h"
/*
+ - * / ( ) #
+ '>', '>', '<', '<', '<', '>', '>',
- '>', '>', '<', '<', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'<', '<', '<', '<', '<', '=', '~',
'>', '>', '>', '>', '~', '>', '>',
'<', '<', '<', '<', '<', '~', '='
纵坐标是前一个符号,横坐标是当前符号。>代表前一个的优先级高于当前符号,
<代表前一个低于当前,=代表运算完成
*/
//+ - * / ( ) #
char priority[7][7] =
{
'>', '>', '<', '<', '<', '>', '>',
'>', '>', '<', '<', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'>', '>', '>', '>', '<', '>', '>',
'<', '<', '<', '<', '<', '=', '~',
'>', '>', '>', '>', '~', '>', '>',
'<', '<', '<', '<', '<', '~', '='
};
int is_operand(char c)
{
if(c >= '0' && c <= '9' )
{
return true;
}
else
{
return false;
}
}
int get_pos(char c)
{
//+ - * / ( ) #
switch(c)
{
case '+':
return 0;
case '-':
return 1;
case '*':
return 2;
case '/':
return 3;
case '(':
return 4;
case ')':
return 5;
case '#':
return 6;
default:
return -1;
}
}
int get_priority(char old, char cur)
{
int y = get_pos(cur);
int x = get_pos(old);
return priority[x][y];
}
int operate(char opnd1, char optr, char opnd2)
{
int a = opnd1 - '0';
int b = opnd2 - '0';
int result = 0;
switch(optr)
{
case '+':
result = a+b ;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
result = a/b;
break;
default:
return -1;
}
return result+'0';
}
void caculate_expression()
{
SQSTACK *head_optr = NULL;
SQSTACK *head_opnd = NULL;
init_stack(&head_optr);
init_stack(&head_opnd);
push_stack(head_optr, '#');
char c = getchar();
char top_item, optr,opnd_1,opnd_2;
int result;
do
{
if(true == is_operand(c))
{
push_stack(head_opnd, c);
c = getchar();
continue;
}
get_top(head_optr, &top_item);
switch(get_priority(top_item, c))
{
case '<':
push_stack(head_optr, c);
c = getchar();
break;
case '=':
pop_stack(head_optr, &top_item);
if(c != '#')
c = getchar();
break;
case '>':
pop_stack(head_optr, &optr);
pop_stack(head_opnd, &opnd_2);
pop_stack(head_opnd, &opnd_1);
result =operate(opnd_1, optr, opnd_2);
if(-1 == result)
{
printf("operate error\n");
exit(-1);
}
push_stack(head_opnd, (char)result);
break;
case '~':
printf("enter a wrong expression\n");
exit(-1);
break;
default:
break;
}
}while(c != '#' || top_item != '#');
pop_stack(head_opnd, &top_item);
printf("the last value is %d\n", top_item - '0');
clear_stack(head_opnd);
clear_stack(head_optr);
return;