Prefix suffix expression, prefix suffix expression

Source: Internet
Author: User

Prefix suffix expression, prefix suffix expression

They are all expressions. The difference between them is that the operators are different from the locations of the operands: the operators of the prefix expressions are located before their related operands; the same is true for the infix and suffix.

Convert an infix expression to a prefix expression

(1) initialize two stacks: Operator stack S1 and stack S2 that stores intermediate results;
(2) scan the infix expression from right to left;
(3) press the operand into S2;
(4) When an operator is encountered, compare its priority with the S1 stack top operator:
(4-1) If S1 is empty or the top-end operator of the stack is ")", the operator is directly added to the stack;
(4-2) Otherwise, if the priority is higher or equal to the top operator of the stack, the operator is also pushed to S1;
(4-3) otherwise, the operator at the top of the S1 stack will pop up and press it into S2, and then go to (4-1) again to compare with the operator at the top of the new stack in S1;
(5) parentheses:
(5-1) if it is a right brace ")", Press it directly into S1;
(5-2) if it is a left brace "(", the operator at the top of the S1 stack is popped up and pushed to S2 until the right brace is encountered. At this time, this pair of parentheses is discarded;
(6) Repeat steps (2) to (5) until the leftmost part of the expression;
(7) pop up the remaining operators in S1 and press them into S2;
(8) The elements in S2 are displayed and output in sequence. The result is the prefix expression corresponding to the infix expression.

Implementation Code:

int priority(char c){    if (c == '(')    {        return 0;    }    else if (c == '+' || c == '-')    {        return 1;    }    else if (c == '*' || c == '/')    {        return 2;    }    else if (c == ')')    {        return 3;    }}void in2pre(char *dest, const char *src){    stack<char> num;    stack<char> opt;    for (int i = strlen(src) - 1; i >= 0; i--)    {        if (src[i] >= '0' && src[i] <= '9')        {            num.push(src[i]);        }        else if (opt.empty() || priority(src[i]) >= priority(opt.top()))        {            opt.push(src[i]);        }        else        {            while (!opt.empty() && opt.top() != ')')            {                num.push(opt.top());                opt.pop();            }            if (src[i] == '(')            {                opt.pop();            }            else            {                opt.push(src[i]);            }        }    }    while (!opt.empty())    {        num.push(opt.top());        opt.pop();    }    int i = 0;    while (!num.empty())    {        dest[i++] = num.top();        num.pop();    }    dest[i] = '\0';}
Convert an infix expression to a suffix expression

(1) initialize two stacks: Operator stack S1 and stack S2 that stores intermediate results;
(2) scan the infix expression from left to right;
(3) press the operand into S2;
(4) When an operator is encountered, compare its priority with the S1 stack top operator:
(4-1) If S1 is null, or the top-end operator of the stack is left brackets (), the operator is directly added to the stack;
(4-2) Otherwise, if the priority is higher than the top operator of the stack, the operator is also pushed to S1 (note that the conversion to prefix expressions has a higher or the same priority, this does not include the same situation );
(4-3) otherwise, the operator at the top of the S1 stack will pop up and press it into S2, and then go to (4-1) again to compare with the operator at the top of the new stack in S1;
(5) parentheses:
(5-1) if it is a left brace "(", Press it directly into S1;
(5-2) if it is the right brace ")", the operator at the top of the S1 stack is popped up and pushed to S2 until the left brace is encountered. At this time, this pair of parentheses is discarded;
(6) Repeat steps (2) to (5) until the rightmost side of the expression;
(7) pop up the remaining operators in S1 and press them into S2;
(8) The elements in S2 are displayed and output in sequence. The reverse order of the result is the suffix expression corresponding to the infix expression (no reverse order is required when the prefix expression is converted ).

Implementation Code:

Int priority (char c) {if (c = '+' | c = '-') {return 1 ;} else if (c = '*' | c = '/') {return 2;} else if (c = '(') {return 3 ;} else if (c = ') {return 0 ;}} void in2post (char * dest, const char * src) {stack <char> num; stack <char> opt; for (int I = 0; I <strlen (src); I ++) {if (src [I]> = '0' & src [I] <= '9') {num. push (src [I]); // number directly into Stack} else if (opt. empty () | priority (src [I])> p Riority (opt. top () {// opt is empty, the current element is left parenthesis, or the current element has a higher priority than the top element opt. push (src [I]);} else {while (! Opt. empty () & opt. top ()! = '(') {Num. push (opt. top (); opt. pop ();} if (src [I] = ') {opt. pop (); // if the current element is a right bracket, the left bracket} else {opt. push (src [I]); // if the current element is an operator, the inbound stack }}while (! Opt. empty () {num. push (opt. top (); opt. pop ();} int len = num. size (); dest [len] = '\ 0'; while (! Num. empty () {dest [-- len] = num. top (); num. pop ();}}
Evaluate expressions

Common functions:

int compute(int a, char opt, int b){    switch (opt)    {    case '+':        return a + b;    case '-':        return a - b;    case '*':        return a * b;    case '/':        return a / b;    }}
Evaluate prefix expressions

Scan from right to leftExpression. When a number is encountered, the number is pushed into the stack. When an operator is encountered, the two numbers at the top of the stack are displayed, and corresponding calculations are performed using the operator (Top element of stack op top Element), And the result is added to the stack. Repeat the above process until the leftmost end of the expression, and the final value obtained by the operation is the result of the expression.

int prevalue(const char *str){    stack<int> num;    int sum;    for (int i = strlen(str) - 1; i >= 0; i--)    {        if (str[i] >= '0' && str[i] <= '9')        {            num.push(str[i] - '0');        }        else        {            int a = num.top();            num.pop();            int b = num.top();            num.pop();            sum = compute(a, str[i], b);            num.push(sum);        }    }    return num.top();}
Suffix expression evaluate

Scan left to rightExpression. When a number is encountered, the number is pushed into the stack. When an operator is encountered, the two numbers at the top of the stack are displayed, and corresponding calculations are performed using the operator (Top element op stack top Element), And the result is added to the stack. Repeat the above process until the rightmost end of the expression, and the final value obtained by the operation is the result of the expression.

int postvalue(const char *str){    stack<int> num;    int sum;    for (int i = 0; i < strlen(str); i++)    {        if (str[i] >= '0' && str[i] <= '9')        {            num.push(str[i] - '0');        }        else        {            int a = num.top();            num.pop();            int b = num.top();            num.pop();            sum = compute(b, str[i], a);            num.push(sum);        }    }    return num.top();}
Infix expression evaluate

Create two stacks, num and opt, to store the operands and operators respectively,Scan left to rightExpression, onlyThe priority of the current element is higher than that of the top element of the stack.The operator and the operand are displayed for calculation until the top operator of the stack has a higher priority than the current element, and then the current operator is added to the stack (if the current operator is a right brace, the stack is not included. At the same time, the corresponding left brackets are output to the stack) until all operations are completed. When there is only one element left in the operand stack, the value of this element is the result of the expression summation.

int priority(char c){    if (c == '+' || c == '-')    {        return 1;    }    else if (c == '*' || c == '/')    {        return 2;    }    else if (c == '(')    {        return 3;    }    else if (c == ')')    {        return 0;    }}int invalue(const char *str){    stack<int> num;    stack<char> opt;    for (int i = 0; i < strlen(str); i++)    {        if (str[i] >= '0' && str[i] <= '9')        {            num.push(str[i] - '0');        }        else if (opt.empty() || opt.top() == '(' || priority(str[i]) > priority(opt.top()))        {            opt.push(str[i]);        }        else        {            while (!opt.empty() && priority(opt.top()) > priority(str[i]))            {                char c = opt.top();                if (c == '(')                {                    break;                }                opt.pop();                int a = num.top();                num.pop();                int b = num.top();                num.pop();                int sum = compute(b, c, a);                num.push(sum);            }            if (str[i] == ')')            {                opt.pop();            }            else            {                opt.push(str[i]);            }        }    }    while (!opt.empty())    {        char c = opt.top();        opt.pop();        int a = num.top();        num.pop();        int b = num.top();        num.pop();        int sum = compute(b, c, a);        num.push(sum);    }    return num.top();}

Note: The code in this article is mainly used to reflect the algorithm IDEA. To make the program simpler, the operand range is assumed to be a range of [0, 9].

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.