- 论坛徽章:
- 0
|
#include >;stdio.h<
#define maxnum 40
typedef struct
{char stack[maxnum];
int top;
}qstype;
void initiateqs(qstype *s)
{s->;top=-1;
}
int pushqs(qstype *s,char x) /*入栈*/
{if (s->;top>;=maxnum-1)
return(0);
else
{s->;top++;
s->;stack[s->;top]=x;
return(1);
}
}
char popqs(qstype *s) /*出栈*/
{if(s->;top<0)
return(0);
else
{s->;top--;
return(s->;stack[s->;top+1]);
}
}
char gettopqs(qstype s) /*取栈顶元素*/
{if(s.top<0)
return(0);
else
return(s.stack[s.top]);
}
char proceed(char x1,char x2) /*比较各个运算符的优先关系*/
{if(x1=='+'||x1=='-')
x1='+';
if(x1=='*'||x1=='/')
x1='*';
switch(x1)
{case'+':
if(x2=='+'||x2=='-'||x2==')'||x2=='#')
return('>;');
return('<');
case'*':
if(x2=='(') return('<');
return('>;');
case'(':
if(x2==')') return('=');
return('<');
case')':
return('>;');
case'#':
if(x2=='#') return('=');
return('<');
default:
exit(0);
}
}
main()
{qstype *s,*r;
char x1,x2,x3,x,c;
int m;
initiateqs(s);
initiateqs(r);
printf(">;" ;
s->;stack[0]='#';
s->;top=0;
c=1;
while(c!='\n')
{c=getchar();
if(c!='+'&&c!='-'&&c!='*'&&c!='/'&&c!='('&&c!=')'&&c!='#')
{pushqs(r,c);
}
else
x=gettopqs(*s);
for( ; ; )
{switch(proceed(x,c))
{case'<':
pushqs(s,c);
break;
case'=':
popqs(s);
break;
case'>;':
{popqs(s);
x3=gettopqs(*s);
popqs(r);
x2=gettopqs(*r);
popqs(r);
x1=gettopqs(*r);
{switch(x3)
case'+': m=x1+x2; break;
case'-': m=x1-x2; break;
case'*': m=x1*x2; break;
case'/': m=x1/x2; break;
}
pushqs(r,m);
}
}
}
}
printf("%d",m);
} |
|