#include<stdio.h>
#define maxsize 10000
typedef struct
{
char data[maxsize]; //存放栈中元素
int top; //栈顶指针
}SqStack;
//初始化栈
void initStack(SqStack &st)
{
st.top = -1;
}
int isEmpty(SqStack st)
{
if(st.top==-1)return 1;
else
return 0;
}
void Push(SqStack &S,char e)
{
if(S.top==maxsize-1)
return;
S.data[++S.top]=e;
}
void Pop(SqStack &S,char &e)
{
if(isEmpty(S))
{
e='\0';
return ;
}
e=S.data[S.top--];
}
char getPop(SqStack &S)
{
if(isEmpty(S))return 0;
return S.data[S.top];
}
//输出栈中的元素
int print_S(SqStack st)
{
if( isEmpty(st) )
{
printf("Stack is Empty");
return 0;
}
int iPointer = st.top;
while(iPointer != -1)
{
printf("%d ",st.data[iPointer]);
--iPointer;
}
printf("\n");
return 1;
}
int precede(char ch1,char ch2)
{
if(ch1=='+'||ch1=='-')
{
if(ch2=='+'||ch2=='#'||ch2=='-'||ch2==')')
return 1;
else
return 3;
}
else if(ch1=='*'||ch1=='/')
{
if(ch2=='(')
return 3;
else
return 1;
}
else if(ch1=='(')
{
if(ch2==')')return 2;
else return 3;
}
else if(ch1=='#')
{
if(ch2=='#')return 2;
else return 3;
}
}
char hb(char b,char ch,char a)
{
int a1,b1,c;
char c1;
a1=a-'0';
b1=b-'0';
if(ch=='+')
c=a1+b1;
else if(ch=='-')
c=a1-b1;
else if(ch=='*')
c=a1*b1;
else if(ch=='/')
c=a1/b1;
c1=c+'0';
//printf("a=%d b=%d c=%d",a1,b1,c);
return c1;
}
int cal(SqStack &optr,SqStack &opnd)
{
int x;
char a,b,x1;
char ch,ch1;
Push(optr,'#');
scanf("%c",&ch);
while(ch!='#'||getPop(optr)!='#')
{
//printf("getPop(optr)=%c\n",getPop(optr));
if(ch>='0'&&ch<='9')
{
Push(opnd,ch);
//printf("111ch=%c\n",ch);
scanf("%c",&ch);
/* printf("getPop(optr)=%c\n",getPop(optr));
Pop(optr,ch);
printf("getPop(optr)=%c\n",getPop(optr));*/
}
else
{
// printf("2222ch=%c\n",ch);
//printf("precede(getPop(optr))=%d\n",precede(getPop(optr),ch));
switch(precede(getPop(optr),ch))
{
printf("%d",precede(getPop(optr),ch));
case 1:Pop(optr,ch1);Pop(opnd,a);Pop(opnd,b);Push(opnd,hb(a,ch1,b));break;
case 2:Pop(optr,ch);scanf("%c",&ch);break;
case 3:Push(optr,ch);scanf("%c",&ch);break;
}
//printf("getPop(opnd)=%c\n",getPop(opnd));
}
}
/*printf("getPop(optr)=%c\n",getPop(optr));
Pop(optr,ch);
printf("getPop(optr)=%c\n",getPop(optr));*/
//printf("ch=%c\n",ch);
Pop(opnd,x1);
/*printf("%d\n",x1);
Pop(opnd,x1);
printf("%d\n",x1);
Pop(opnd,x1);
printf("%d\n",x1);*/
x=x1-'0';
return x;
}
int main()
{
int s;
char x;
SqStack optr,opnd;
initStack(optr);
initStack(opnd);
s=cal(optr,opnd);
printf("%d\n",s);
return 0;
}
综合训练:试编写算法,利用栈实现表达式求值算法。要求输入数字为个位数,表达式以#结束。
最新推荐文章于 2022-04-09 14:54:14 发布