2019315栈的应用:表达式的计算

#include<iostream>
#include<stack>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

using namespace std;


//优先级函数
int f(char x)
{
    if(x=='*'||x=='/') return 3;
    else if(x=='#')return 0;
    else return 2;
}
int main()
{
    char a[100]="4 + 2 * 5 - 7 + 11 #";//注:数字与符号是用空格分开的。 结果为18 
    char* tx;
    char b2[100];
    int b1[100];
    tx=strtok(a," ");
    int j=0,i=0;
    while(tx)
    {
        char x=*tx;
        if(x>='0'&&x<='9') {b1[i]=atoi(tx);i++;}
        else {b2[j]=x;j++;}

        tx=strtok(NULL," ");//注,分割字符一定是字符串标识,而不是字符标识。‘ ’会出错。


    }
    b2[j]='\0';
    int n=i,m=j;
    cout<<b2<<endl;
    for(int k=0;k<n;k++)
        cout<<b1[k]<<" ";



     stack<int> s1,s2;

     for(int k=0;k<n;k++)
     {

        s1.push(b1[k]);






               while(!s2.empty()&&!(f(b2[k])>f(s2.top())))


               {
                   char s=s2.top();
                   s2.pop();
                   if(s=='*')
                   {
                   int t;
                   int t1=s1.top();
                   s1.pop();
                   int t2=s1.top();
                   s1.pop();
                   t=t1*t2;
                   s1.push(t);


                   }
                    else if(s=='/')
                   {int t;
                   int t1=s1.top();
                   s1.pop();
                   int t2=s1.top();
                   s1.pop();
                   t=t2/t1;//注意 t2 t1顺序
                   s1.push(t);



                   }
                   else if(s=='+')
                   {int t;
                   int t1=s1.top();
                   s1.pop();
                   int t2=s1.top();
                   s1.pop();
                   t=t1+t2;
                   s1.push(t);
                   }
                    else if(s=='-')
                   {int t;
                   int t1=s1.top();
                   s1.pop();
                   int t2=s1.top();
                   s1.pop();
                   t=t2-t1;//注意t2,t1顺序
                   s1.push(t);
                   }
               }


 s2.push(b2[k]);


if(s2.top()=='#') {cout<<endl;cout<<s1.top();break;}




     }




cout<<endl;
cout<<(char)s2.top();


                   cout<<endl;

cout<<s1.top();


    return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值