您的位置:首页 > 编程语言 > C语言/C++

在C++中使用栈来把中缀表达式转换为后缀表达式并求值,简单明了

2016-07-12 18:31 369 查看
                
#include<iostream>

#include<stdlib.h>//头文件包含atoi()函数

using namespace std;

typedef char T;

class stack{

T data[100];

int sz;

public:

stack() :sz(){}

void push(const T& d){

if (full()) throw "满";

data[sz++] = d;

}

void pop(){

if (empty()) throw "空";

sz--;

}

T top(){

if (empty()) throw"空";

return data[sz - 1];


}

T undertop(){

if (empty()) throw"空";

return data[sz-2];

}

int Ssz(){//返回栈的元素数量

return sz;

}

char Sdata(const int i){//返回栈相应位置的元素,栈低为位置0

return data[i];

}


bool empty(){ return sz == 0; }

bool full(){ return sz == 100; }

};

//c1高于c2返回true,否则返回false

bool prior(char c1, char c2){

return (c1 == '*' || c1 == '/') && (c2 == '+' || c2 == '-');

}

int main()

{

string str = "1+4";

stack res;//结果栈

stack exp;//运算栈

stack cres;//计算结果栈

stack num;//计算运算栈


char ch;


for (int i = 0; i<str.length(); i++){

ch = str[i];

if (ch >= '0'&&ch <= '9'){//是数字的话就把ch放入res结果栈中

res.push(ch);

}

else if ('(' == ch){

exp.push(ch);

}

else if (')' == ch){

while (exp.top() != '('){

res.push(exp.top());

exp.pop();

}

exp.pop();

}

else{//是运算符

while (!exp.empty() && exp.top() != '('//当exp运算栈不为空且栈顶元素不为'('且ch优先级低于或等于栈顶元素

&&!prior(ch, exp.top())){

res.push(exp.top());

exp.pop();

}

exp.push(ch);

}

}

while (!exp.empty()){

res.push(exp.top());

exp.pop();

}

cres=res;


while (!res.empty()){

cout << res.top();

res.pop();

}

cout << endl;

cout<<"-----------------"<<endl;

for(int i=0;i<cres.Ssz();i++){

if(cres.Sdata(i)>='0'&&cres.Sdata(i)<='9'){//如果是数字就放入数字栈

num.push(cres.Sdata(i));

}

else if(cres.Sdata(i)=='*'){//如果符号是乘号

// a=atoi(num.top())*atoi(num.undertop());//atoi()把字符串转化为整形数

int a=(num.undertop()-48/*或者0*/)*(num.top()-48/*或者0*/);//字符减去48就转化成int型

char c=a+'0';   //int型加上'0'就转化为char型

num.pop();

num.pop();

num.push(c);

}

else if(cres.Sdata(i)=='/'){

int a=(num.undertop()-48)/(num.top()-48/*或者0*/);

char c=a+'0';

num.pop();

num.pop();

num.push(c);

}

else if(cres.Sdata(i)=='+'){

int a=(num.undertop()-48/*或者0*/)+(num.top()-48/*或者0*/);

char   c=a+'0';

 num.pop();

 num.pop();

 num.push(c);

}

else if(cres.Sdata(i)=='-'){

int a=(num.undertop()-48/*或者0*/)-(num.top()-48/*或者0*/);

char   c=a+'0';

 num.pop();

 num.pop();

 num.push(c);

}

}

cout<<num.top()<<endl;

}


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++