Parenthesized expression evaluation (reference algorithm Notes)

Although the algorithm is very simple principle, but there are a few areas that need attention.
1. Because the left parenthesis is to be placed in the operator stack, so his priority is set to 0, or to other operators, and do not know can not go into.
2. The top of the stack is less than the priority of the operator op, the operator can be placed into the stack.


    #include <bits/stdc++.h>
using namespace std;

struct node  {
	double num;
	char op;
	bool flag;
};
string str;
stack<node>s;
queue<node>q;
map<char,int>op;
void change() {
	double num;
	node temp;
	for(int i=0;i<str.length();i++) {
        char c=str[i];
		if(c>='0'&&c<='9') {
			temp.flag=true;
			temp.num=c-'0';
			q.push(temp);
		} else {
			
			
			if(c==')') {
				while(!s.empty() &&s.top().op!='(') {
					q.push(s.top());
					s.pop();
				}
				s.pop();
				continue;
			} else if(c!='('){

				while(!s.empty() && op[c]<=op[s.top().op]) {
					q.push(s.top());
					s.pop();
				}

			}temp.flag=false;
			temp.op=c;
			s.push(temp);
		}
	}

	while(!s.empty()){
		q.push(s.top());
		s.pop();
	}//从操作符栈变成了空栈 
}
double cal(){
	double temp1,temp2;
	node cur,temp;
	while(!q.empty()){
		cur=q.front();
		q.pop();
		if(cur.flag==true)s.push(cur);
		 else {
		 	temp2=s.top().num;
		 	s.pop();
		 	temp1=s.top().num;
		 	s.pop();
		 	temp.flag=true;
		 	if(cur.op=='+')temp.num=temp1+temp2;
			if(cur.op=='-')temp.num=temp1-temp2;
			if(cur.op=='*')temp.num=temp1*temp2;
			if(cur.op=='/')temp.num=temp1/temp2;
			s.push(temp);
			  
		 }
	}return s.top().num;
}
int main(int argc, char **argv) {
    op['(']=0;
	op['+']=op['-']=1;
	op['*']=op['/']=2;
	getline(cin,str);
		change();
		printf("%.2f",cal());
	

	return 0;
}


Published 17 original articles · won praise 5 · Views 2362

Guess you like

Origin blog.csdn.net/ilikecarrots/article/details/94554460