70,037
社区成员
发帖
与我相关
我的任务
分享#include <stdio.h>
#include <stdlib.h>
#define Stack_Size 50
#define true 1
#define false 0
typedef char Elemtype;
typedef struct
{
Elemtype elem[Stack_Size];
int top;
}SeqStack;
void InistStack(SeqStack *S)
{
S->top=0;
}
void Push(SeqStack *S, Elemtype x)
{
if(S->top==Stack_Size)
return -1;
S->elem[S->top]=x;
S->top++;
}
void Pop(SeqStack *S, Elemtype *x)
{
if(S->top==0) return -1;
else
{
S->top--;
*x=S->elem[S->top];
}
}
char GetTop(SeqStack S,char *x)
{
if(S.top==0) return false;
else
{
*x=S.elem[S.top-1];
}
}
char Precede(char a,char b)
{
if(a=='#')
if(b=='#')
return '=';
else
return '<';
if(a=='+'||a=='-')
if(b=='+'||b=='-'||b==')'||b=='#')
return '>';
else
return '<';
if(a=='*'||a=='/')
if(b=='(')
return '<';
else
return '>';
if(a=='(')
if(b==')')
return '=';
else
return '<';
if(a==')')
return '>';
}
int Operate(int a,char theta,int b)
{
int result;
switch(theta)
{
case'+':return a+b;
case'-':return a-b;
case'*':return a*b;
case'/':
if(b!=0)
return a/b;
else
{
printf("Divisor can not Be zero!\n");
exit(0);
}
}
}
main()
{
SeqStack OPTR,OPND;
InistStack(&OPTR);
Push(&OPTR,'#');
InistStack(&OPND);
int a,b;
char c=getchar();
char x,y,theta;
GetTop(OPTR,&x);
while(c!='#'||x!='#')
{
if(c>='0'&&c<='9')
{
Push(&OPND,c);
c=getchar();
}
else
{
switch(Precede(x,c))
{ case '<':
Push(&OPTR,c); c=getchar();
break;
case '=':
Pop(&OPTR,&x); c=getchar();
case '>':
Pop(&OPTR,&theta);Pop(&OPND,&b);Pop(&OPND,&a);
Push(&OPND,Operate(a,theta,b));
break;
}
}
GetTop(OPTR,&x);
}
GetTop(OPND,&y);
printf("%d",y);
}