Application of data structure Java to implement--① stack--> stack three, arithmetic expression evaluation __arcinfo

Source: Internet
Author: User
Tags arithmetic

It 's written in front .

Just learn the description of the stack seems very boring, so I deliberately find a few more interesting examples, a deepening of the stack of understanding and use, two, can also open up the idea, this is the case of three
example three, evaluation of arithmetic expressions
1, the problem description
When an arithmetic expression contains more than one operator, and the operators have different precedence, how can an arithmetic expression be processed ....
2. Train of Thought
First, we need to know that the expressions are divided into three categories:
① infix expression: A + (B-C/D) *e
② prefix expression +a*-b/cde
③ suffix expression abcd/-e*+
Because operators have precedence, it is very difficult to compute an infix expression in the computer. In particular, parentheses are even more troublesome, and the prefix expression has neither operator precedence nor parenthesis constraint because the order in which the operators appear in the suffix expression is the order of the calculations, so it is simpler to evaluate the expression of a suffix. Therefore, the process of finding the value of an arithmetic expression can be translated into two procedures: 1. Converts an infix expression to a suffix expression of 2. Evaluate the suffix expression One, will be infix into a suffix
Because the order in which operators appear is always the same as the actual arithmetic sequence, so the precedence and parentheses are the first, so use a stack to keep the operators that are not sent to the suffix expression, which is called the operator stack algorithm described below: (1) initialize an operator stack (2) reading a character from left to right from a string entered in an arithmetic expression (3) if the current character is an operand, sent directly to the suffix expression (4) if the current character is an opening parenthesis, it is pressed into operation Fu Yi (5) If the current character is an operator, do the following: ① when the operator stack is empty, Press it directly into the stack. ② This operator is pushed onto the stack when the precedence of this operator is higher than the operator at the top of the stack. Otherwise, the pop-up stack top operator is sent to the suffix, and the current operator is pressed on the stack, repeating steps (5) (6) If the current character is a closing parenthesis, repeatedly pops up the top of the stack and sends it to the suffix expression, knowing that the top element of the stack is the left parenthesis, Then leave the parentheses out of the stack and discard (7) If the read has not yet finished, repeat steps (2) (8) If the read ends, all remaining operators in the stack are ejected and sent to the suffix expression
Second, the calculation of the value of the suffix expression is simple, is to find the operator, and then find the last occurrence of two operands, so as to constitute a minimum arithmetic expression to operate, in the calculation process also need to use a stack to retain the suffix in the expression is not involved in the operation of the operand, known as the operand stack, the algorithm described as follows: (1) Initializing an operand stack (2) reads the character ① in the suffix expression from left to right and presses the operand stack if the current character is the operand. ② if the current character is an operator, then eject two operands from the top of the stack to participate in the operation, and the result of the operation into the operand stack. (3) Repeat step (2) until the end of the read suffix expression, the stack top element in the operand stack is the result of the suffix expression

3, code implementation

Package Org.

Stone6762.MStack.adopt;

Import Java.util.Scanner; import org.
Stone6762.MStack.imple.LinkStack; /** * @author_Stone6762/public class Arithexpevaluation {/** * @Describe_ converts the original expression to a suffix expression * @param expression The original expression * @return The suffix expression relative to the element expression * @throws Exception/public String Conver2postfix (String expression) throws Excep tion {Linkstack st = new Linkstack ()//operator stack String postFix = "";//suffix expression for (int i = 0; Expression!= null && i < expression.length (); i++) {char c = expression.charat (i);//traversal, if the operand is an operator if ('!= c) {//character cannot be an empty if (Isopenparenthesis (c)) {//
				Left parenthesis//left parenthesis on stack St.push (c); else if (Iscloseparenthesis (c)) {//closing parenthesis//closing parenthesis to put all the operators out of the stack know to encounter an opening parenthesis, and then put the left parenthesis out of the stack and discard Character ac = (Character) St
					. Pop ();
						while (!isopenparenthesis (AC)) {PostFix + = ac.tostring (); AC = (Character) st.pop ()//If the left parenthesis is taken out, it is obvious that the} else if (Isoperator (c)) {//Operator/* * If the stack is empty, go directly into the stack. If the stack is notEmpty, you need to compare the precedence of the stack top operator to the precedence of the operator to be put into the stack * stack the operators that are higher in the stack than the operators you want to stack into. The operator is then put into the stack/if (!st.isempty ()) {//If the stack is not empty, you need to determine
						Character AC = (Character) st.pop ();
							while (AC!= null && priority (Ac.charvalue ()) > Priority (c)) {PostFix = AC;
							AC = (Character) st.pop ();
						Because it is the first to take out after the judge is, so if the jump out of the loop need to put the last removed operator into the stack}///The last removed priority of the operator into the stack if (AC!= null) {St.push (AC);
				}//Finally, put the operator into the stack st.push (c);
				else {//operand, added directly to the suffix expression PostFix = c;
		At the end, if the stack is not empty, all operators in the stack are required to concatenate to the end of the suffix expression while (!st.isempty ()) {PostFix + = St.pop (). toString ();
	return postFix; /** * @Describe_ The suffix expression is computed * @param postfix suffix expression * @return The result of the calculation * @throws Exception */public double numb Ercalculate (String PostFix) throws Exception {Linkstack st = new Linkstack ();//operand stack for (int i = 0; i < POSTFIX.L Ength ();
			i++) {char c = postfix.charat (i); if (Isoperator (c)) {Double D2 = double.valueof (St.pop (). toString ());
				Double D1 = double.valueof (St.pop (). toString ());
				Double d3 = 0;
					Switch (c) {case ' + ': d3=d1+d2;
				Break
					Case '-': d3=d1-d2;
				Break
					Case ' * ': d3=d1*d2;
				Break
					Case '/': D3=D1/D2;
				Break
					Case '% ': d3=d1%d2;
				Break
					Case ' ^ ': D3=math.pow (D1, D2);
				
				Break
				Default:break;
			St.push (D3);//The results after the operation into the stack}else{//when the operand is, directly into the operand stack st.push (c);
	} return (double) St.pop ();
		/** * @Describe_ The precedence of the operator/private int priority (char c) {switch (c) {case ' ^ ': return 3;
		Case ' * ': Case '/': Case '% ': return 2;
		Case ' + ': Case '-': return 1;
	return 0; /** @Describe is an operator _/private Boolean isoperator (char c) {if (' + ' = c | | '-' = = c | | ' * ' = = c | | '/' = c | | ' ^ ' = = c | |
		'% ' = = C ' {return true;
	return false; /** @Describe is a closing parenthesis _ * * Private Boolean IscloSeparenthesis (char c) {return ') ' = = C;
	/** @Describe_ Determine if it is a left parenthesis/private Boolean isopenparenthesis (char c) {return ' (' = = C;
		public static void Main (string[] args) throws Exception {arithexpevaluation p=new arithexpevaluation ();
		Scanner scan = new Scanner (system.in);
		System.out.println ("Please enter an arithmetic expression:");
			while (Scan.hasnext ()) {String str=scan.next ();
			String Postfix=p.conver2postfix (str);
			SYSTEM.OUT.PRINTLN ("The result is:" +p.numbercalculate (PostFix));
			System.out.println ();
		System.out.println ("Please enter an arithmetic expression:");
 }
		
	}
}


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.