#include <stdlib.h>
#include <stdio.h>
struct s_node
{
int data;
struct s_node *next;
};
typedef struct s_node s_list;
typedef s_list *link;
link operate = NULL;
link operand = NULL;
//存入堆栈数据
link push(link stack,int value)
{
link newnode;
newnode = (link)malloc(sizeof(s_list));
if (!newnode)
{
printf("Memory allocation failure!/n");
return NULL;
}
newnode->data = value;
newnode->next = stack;
stack = newnode;
return stack;
}
//取出数据
link pop(link stack,int *value)
{
link top;
if ( NULL != stack )
{
top = stack;
stack = stack->next;
*value = top->data;
free(top);
return stack;
}
else
{
*value = -1;
}
}
//检查堆栈是否为空
int empty(link stack)
{
if ( NULL == stack )
{
return 1;
}
else
{
return 0;
}
}
//判断是否为运算符
int is_operator(char operate)
{
switch(operate)
{
case '+':
case '-':
case '*':
case '/':
return 1;
default:
return 0;
}
}
//判断运算符优先权
int priority(char operate)
{
switch(operate)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
//计算两个操作数的值
int caculate(int operate,int operand1,int operand2)
{
switch(operate)
{
case '+':
return (operand2+operand1);
case '-':
return (operand2-operand1);
case '*':
return (operand2*operand1);
case '/':
return (operand2/operand1);
}
}
int main(void)
{
char expression[50];
int position=0;
int op=0;
int operand1=0;
int operand2=0;
int result=0;
printf("Please input the expression:");
gets(expression);
printf("/n");
while (expression[position] != '/0' && expression[position] != '/n')
{
if (is_operator(expression[position]))
{
if (!empty(operate))
{
while (!empty(operate)&&priority(expression[position])<priority(operate->data))
{
operand=pop(operand,&operand1);
operand=pop(operand,&operand2);
operate=pop(operate,&op);
operand=push(operand,caculate(op,operand1,operand2));
}
}
operate=push(operate,expression[position]);
}
else
{
operand=push(operand,expression[position]-48);
}
position++;
}
while (!empty(operate))
{
operate=pop(operate,&op);
operand=pop(operand,&operand1);
operand=pop(operand,&operand2);
operand=push(operand,caculate(op,operand1,operand2));
}
operand=pop(operand,&result);
printf("the expression [%s] result is '%d'/n",expression,result);
return 0;
}