Java infix expression-to-suffix expression

Source: Internet
Author: User

Arithmetic is one of the important applications of stack

Infix expression-to-suffix expression (inverse Polish algorithm) process
    1. Iterating through infix expressions from left to right
    2. Digital direct output as part of the suffix expression
    3. If it is a symbol, the priority of the top element of the stack is judged
    4. Above stack top element priority directly into the stack
    5. The top element of the stack top priority stack is below or equal to the stack and output as part of the suffix expression (note that this is the precedence of the top element of the recursive comparison stack and out of the stack), and finally the current element into the stack
      Until the infix expression is traversed, the final output suffix expression
The following is their own implementation of the source code
Package Com.yhq.demospringboot;import Org.apache.commons.lang3.stringutils;import Java.util.*;import java.util.concurrent.linkedblockingqueue;/** * YANGHQ * 2018/3/12 */public class Pretoafterutil {private static String le Ftchar = "(";p rivate static String Rightchar = ")";p rivate static map<string, integer> Operationsymbolmap = new Hash Map<> (); static {//Initialize symbol and Priority operationsymbolmap.put (")", 00);        The closing parenthesis needs to match the opening parenthesis, so the lowest priority operationsymbolmap.put ("+", 10);        Operationsymbolmap.put ("-", 10);        Operationsymbolmap.put ("*", 20);        Operationsymbolmap.put ("/", 20); Operationsymbolmap.put ("(", 30);} /** * infix expression converted to suffix expression * @param strings * @return */public Queue parsepre (string[] strings) {stack<string> PreS        Tack = new stack<string> ();        queue<string> queue = new Linkedblockingqueue ();        int i = 0; while (I<strings.length && objects.nonnull (Strings[i])) {if (Stringutils.isnumeric (Strings[i]) {Queue.add (strings[i]);                                }else if (Stringutils.isnotempty (Strings[i])) {if (Prestack.isempty ()) {                        Prestack.push (Strings[i]);                                } else {String top = Prestack.pop ();                                                if (Comparepriority (Strings[i], top) < 0) {if (Top.equals (Leftchar)) {                                                Prestack.push (top);                                        Prestack.push (Strings[i]);                                                }else if (strings[i].equals (Rightchar)) {appendTo (queue, top);                                        Prestack.pop ();                                                } else{appendTo (queue, top); Poppre (Prestack, strings[i], qUeue); Prestack.push (Strings[i]);                                        Current element into stack}} else {                                        Prestack.push (top);                                Prestack.push (Strings[i]);        }}} i++;        } while (!prestack.isempty ()) {Queue.add (Prestack.pop ()); } return queue;} /** * Recursive comparison of the current element with the top element of the stack priority * @param PRESTATCK * @param chartemp * @param queue */public void Poppre (stack<string> presta                TCK, string chartemp, queue queue) {if (!prestatck.isempty ()) {String top = Prestatck.pop (); if (Comparepriority (chartemp, top) <= 0) {//below the top of the stack, becomes part of the suffix expression a                        Ppendto (queue, top);                Poppre (PRESTATCK, chartemp, queue);                       } else { Prestatck.push (top);                 }}}private void AppendTo (queue queue, String s) {if (!s.equals (Leftchar) &&!s.equals (Rightchar)) {        Queue.add (s); }}/** * Comparison Priority * @param start * @param to * @return */private int comparepriority (string start, String to) {return Operationsymbolmap.get (Start). CompareTo (Operationsymbolmap.get (To));}        /** * calculate suffix expression result * @param queue * @return */public int computeresult (queue<string> queue) {int result = 0;        if (Objects.isnull (queue)) {return result;        } String s = Queue.poll ();        stack<integer> stack = new stack (); while (Objects.nonnull (s)) {if (Stringutils.isnumeric (s)) {Stack.push (Integer.valueo                F (s)); }else if (!                        Stringutils.isempty (s)) {int first = 0;                        int second = 0; Switch (s) {case ' +": first = Stack.pop ();                                        Second = Stack.pop ();                                        result = first + second;                                        Stack.push (result);                                Break                                        Case "-": first = Stack.pop ();                                        Second = Stack.pop ();                                        result = Second-first;                                        Stack.push (result);                                Break                                        Case "*": first = Stack.pop ();                                        Second = Stack.pop ();                                        result = First * second;                                        Stack.push (result);                                Break Case "/":                                       First = Stack.pop ();                                        Second = Stack.pop ();                                        result = Second/first;                                        Stack.push (result);                        Break        }} s = Queue.poll (); } return result; /** * Test * @param args */public static void main (string[] args) {string[] pre = new string[]{"8", "+", "(", "6", "-", "        1 ",") "," * "," 2 "," + "," 10 ","/"," 2 "};        StringBuilder sb = new StringBuilder ();        for (int i = 0; i < pre.length; i++) {sb.append (pre[i]);        } System.out.println ("prefix expression:" + sb.tostring ());        Queue queue = new Pretoafterutil (). Parsepre (pre);        System.out.println ("suffix expression:" + queue.tostring ()); System.out.println ("suffix expression evaluates:" + New Pretoafterutil (). Computeresult (queue));}}

Output results display
Prefix expression: 8+ (6-1)2+10/2
Suffix expression: [8, 6, 1,-, 2,
, +, 10, 2,/, +]
Suffix expression calculation Result: 23

Java infix expression-to-suffix 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.