Evaluation of expressions using inverse polish

Source: Internet
Author: User

infix expressions and suffix expression diagrams illustrate the use of inverse Polish expressions to evaluate the method, which is implemented using C + +. There is a difference between the implementation and the principle explanation, which needs further refinement.

Rules for converting infix expressions to post-suffix expressions:

Rule: Iterate from left to right each number and symbol of infix expression, if the number is output, is a part of the suffix expression, if the symbol, then the top of the stack to determine the priority, is the right parenthesis or priority lower than the top sign (multiplication and division priority plus minus) then the top of the stack of elements out to find and output, and the current symbol into the stack, Until the final output suffix expression.

The rules above are translated into the following execution rules:

1. Operand encountered: Direct output (added to suffix expression)
2. When the stack is empty, the operator is encountered, directly into the stack
3. Opening parenthesis: Putting it into the stack
4. Closing parenthesis: Performing a stack operation and outputting the elements of the stack until the pop-up stack is an opening parenthesis, and the opening parenthesis does not output.
5. Other operators encountered: subtraction: Eject all the top-priority elements that are greater than or equal to the operator, and then put the operator into the stack
6. Finally, the stack of elements in sequence out of the stack, output.

You need to judge and handle the above 6 cases in the process, and because the number may have multiple digits, the value of the operand is also a problem.


Whether the precedence of the comparison LHS is not higher than the symbol bool RHS,RHS representing the top of the stack priority (char Lhs,char RHS) {if (rhs== ' (') return false; if (lhs== ' + ' | |
		lhs== '-') return true; if (lhs== ' * ' | | lhs== '/') && (rhs== ' * ' | |
		rhs== '/') return true;
return false;
	///convert infix expression to suffix string inprefix2postprefix (String str) {string res;//suffix expression result stack<char> s; for (int i=0;i<str.size (); i++) {//If a number, add the suffix expression result directly if (IsDigit (Str[i)) {while i<str.size () &&
					IsDigit (Str[i])) {res+=str[i];
			i++;
		i--;//note here to reduce I 1, because the above loop will I more right to move a bit, if not minus 1, will miss a res+= ""; else//If it is a symbol, you need to compare it to the top of the stack {///If the stack is empty, press it directly into the stack, or if it is a left parenthesis (s.empty it directly into the stack if () |
				str[i]== ' (') S.push (Str[i]); else {//When the closing parenthesis is encountered, stack the data out of the stack until the opening parenthesis is encountered, noting that the left and right brackets do not need to join the result res if (str[i]== ') ') {while!s.empty () &am
									P;&s.top ()!= ' (')//Note that you need to determine whether the stack is empty {res+=s.top () before performing a top operation on the stack.
									res+= "";
								S.pop ();
						} s.pop ();
	} else {							This indicates that the character is a symbol and is not ' (' and ') ' if (Priority (Str[i],s.top ())]//If its precedence is not higher than the top of the stack, the top symbol is out of stack {while (
												!s.empty () &&priority (Str[i],s.top ())) {res+=s.top ();
												res+= "";
										S.pop ();
						} s.push (Str[i]);//finally remember to put the symbol into the stack} else//If its priority is higher than the top of the stack, then directly into the stack S.push (Str[i]);
		The remaining elements in the stack are added to the result set {Res+=s.top () after the string is traversed by the!s.empty ()}}}}.
		res+= "";
	S.pop ();
return res; }



Above is the method of converting infix expressions to suffix expressions, followed by the method of processing suffix expressions:

Rules: From left to right to traverse the expression of each number and symbol, encountered is a number into the stack, encountered is a symbol, will be in the stack top two digital stack, operation, operation results into the stack, until the final results obtained. Note that the first element that pops up from the top of the stack is the first operand, and the second element that pops up is the second operand, don't reverse the order. The number of times the stack is used to access operations.

int operate (int first,int Second,char op)
{
	int res=0;
	Switch (OP)
	{case
		' + ':
			res= first+second;
			break;
		Case '-':
			Res=first-second;
			break;
		Case ' * ':
			res=first*second;
			break;
		Case '/':
			res=first/second;
			break;
		Default: Break
			;		
	}
	return res;
}
int   calculatebypostprefix (string input)
{
	stack<int> s;
	int tmp=0;
	for (int i=0;i<input.size (); i++)
	{if
		(IsDigit (input[i))//If a number is encountered, the number is put into the stack
		{while
			i< Input.size () &&isdigit (Input[i])
			{
				tmp=10*tmp+input[i]-' 0 ';
				i++;
			}
			After the number is obtained, the input is pressed into the stack
			s.push (TMP);
			i--;
		}
		else if (input[i]== ')//If a space is encountered, reset tmp to 0
			tmp=0;
		else//at this point is the symbol
		{
			   //Take out two operands, and compute
				int second=s.top ();
				S.pop ();
				int first=s.top ();
				S.pop ();
				int local=operate (first,second,input[i]);
				S.push (local);
		}
	Return S.empty () 0:s.top ();


The main functions are as follows:

int main ()
{
	string str;//9+ (3-1) *3+10/2
	cout<< "Please enter a valid expression (+,-, *,/with integer support, bracket operation):" <<endl;
	while (Getline (CIN,STR))
	{
		string ot=inprefix2postprefix (str);
		cout<< "suffix expression is:" <<ot<<endl;
		cout<< "The result is:" <<calculatebypostprefix (OT) <<endl;
		cout<< "Please enter an expression:" <<endl;
	}
	System ("pause");
	return 0;
}

Take the example in the previous article "9+ (3-1) *3+10/2" to test to see the converted suffix expression and the results of the operation, the program supports the continuous input of several sets of data in the console and calculate the results.


Complete code: Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.