这个是自己写的,用来判断 + - * / 的优先级
#include <stdlib.h> /*输入表达式 如 3+8+7*9/2 */struct s_node
{
int data;
struct s_node * next;
};
typedef struct s_node s_link;
typedef s_link *link;
link operand=NULL;
link operator=NULL;
link push (link stack,int value)
{
link new;
new=(link) malloc (sizeof(s_link));
if (!new) printf("allocation failed:\n");
else {
new->data=value;
new->next=stack;
stack=new;
}
return stack;
}
link pop (link stack, int *value)
{
link top;
top=stack;
if (stack!=NULL)
{
stack=stack->next;
*value=top->data;
free(top);
return stack;
}
}
int empty (link stack)
{
if (stack==NULL)
return 1;
else return 0;
}
int is_operator(char operator)
{
switch(operator)
{
case '*' : case '/' : case '+': case '-': return 1;
default: return 0;
}
}
int priority (char operator)
{
switch (operator)
{
case '-': case '+': return 1;
case '*' : case '/' : return 2;
default : return 0;
}
}
int result (int operator, int operand1,int operand2)
{
switch (operator)
{
case '*' : return operand2*operand1;
case '/' : return operand2/operand1;
case '-' : return operand2-operand1;
case '+' : return operand2+operand1;
}
}
void main()
{
char e[50]; int a[5];
int p=0;
int operand1,operand2;
int op;
int evaluate;
printf("\n please input the order expression:");
clrscr();
gets (e);
while (e[p]!='\0' && e[p]!='\n')
{
if (is_operator(e[p]))
{
if (!empty(operator))
{
while (priority(e[p])<=priority(operator->data))
{
operand=pop(operand,&operand1);
operand=pop(operand,&operand2);
operator=pop(operator,&op);
operand=push(operand,result(op,operand1,operand2));
}
}
operator =push(operator,e[p]); p++;
}
else
{
int temp=0;int t=0;int i; int x;int c=0;int b=1;
a[temp]=e[p]-48;
p++;
while (!is_operator(e[p]) && e[p]!='\0')
{
a[++temp]=e[p++]-48;
}
for (i=temp;i>=0;i--)
{
x=i;
while (x)
{
b*=10;
x--;
}
a[c++]*=b;b=1;
}
for (i=temp;i>=0;i--)
t+=a[i];
operand=push (operand,t);
}
}
while (!empty(operator))
{
operator=pop(operator,&op);
operand = pop(operand,&operand1);
operand = pop(operand,&operand2);
operand=push(operand,result(op,operand1,operand2));
}
operand=pop(operand,&evaluate);
printf("the expression [%s] result is '%d'",e,evaluate);
}