#include<stdio.h>
#include<stdlib.h>
#define OK 1000
#define ERROR 1001
struct node
{
char data;
struct node *next;
};
typedef struct node Node;
struct stack
{
int length;
Node *top;
}
typedef struct stack Stack;
int InitStack(Stack *s)
{
s->length=0;
s-top=NULL;
return OK;
}
int EmptyStack (Stack *s)
{
return (NULL== s->top)? OK: ERROR;
}
int Push (Stack *s,char e)
{
Node *p=(Node *)malloc (sizeof(Node));
if(NULL==p)
{
return ERROR;
}
p->data=e;
p->next=s->top;
s->top=p;
return OK;
}
int GeyTop (Stack *s)
{
return (s->top->data);
}
int Priority(char e)
{
switch(e)
{
case '(' :
return 3;
case ‘* ’:
case '/' :
return 2;
case ‘+’:
case '-':
return 1;
default :
return 0;
}
}
char Pop( Stack *s)
{
char e =s->top->data;
Node *p=s->top;
s->top=p->next;
free(p);
s->length - -;
return e;
}
int main ( )
{
Stack opt_stack,num_stack;
char str【100】={0};
int i =0; tmp = 0;
int j;
if(InitStack (&opt_stack)!= OK || InitStack (&num_stack)!= OK)
{
printf("Init Failure\n");
}
printf("Please input : \n");
scanf("%s",str);
while(str[i] != '\0' || EmptyStack(&opt _stack) ! = OK)
{
if (str[i]>='0' && str[i]<='9' )
{
tmp = tmp*10+str[i] -'0';
i++;
if(str[i]< '0'; || str[i]> '9')
{
Push(&num_stack, tmp);
tmp=0;
}
}
else
{
if(EmptyStack(&opt_stack)= OK || (GetTop(&opt_stack)= '(' &&
str[i]!= ' )' ) || Priority (str[i]>Priority (GetTop (&opt_stack) ) )
{
Push( &opt_stack, str[i]);
i++;
comtitue;
}
if (GetTop (& opt_stack)== '(' && str[i] == ‘)’)
{
Pop(&opt_stack);
i++;
contitue;
}
if ((str[i] == ')' && GetTop(&opt_stack)!= '(') ||
(str[i] == '\0' &&EmptyStack(&opt_stack) != OK) ||
(Priority(str[i])<= Priority(GetTop(&opt_stack))) )
{
switch(Pop (& opt_stack))
{
case '+' :
Push( & num_stack,Pop(&num_stack) + Pop (&num_stack));
break;
case '-' :
j =Pop (&num _stack);
Push(& num_stack, Pop (&num _stack)- j);
break;
case '*' :
Push( &num_stack, Pop (&num_stack)* Pop (&num_stack));
break;
case ‘/’:
j=Pop(&num_stack);
Push(&num_stack ,Pop (&num_stack) / j);
break;
}
}
}
}
printf("result is %d \n", Pop (& num_stack));
return 0;
}