Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Data Structures - Expression Parsing

Data Structures - Expression Parsing

Expression parsing (Parsing Expressions) is the most classic application scenario of the stack data structure.

Expression parsing shows how to use a stack to handle the conversion between infix, prefix, and postfix expressions as well as expression evaluation.


Three expression forms

Converting infix expression A + B * C to postfix - step demonstration

Step 1

Read A

Operand, output directly

Output: A

Stack: empty

Step 2

Read +

Operator, push onto stack

Output: A

Stack: +

Step 3

Read B

Operand, output directly

Output: AB

Stack: +

Step 4

Read *

Output: AB

Stack: +*

Step 5

Read C

Operand, output directly

Output: ABC

Stack: +*

Step 6

at the end

Pop all operators from the stack

Output: ABC*+

Stack: empty

Final result: A + B * C -> A B C * +

When processing mathematical expressions in a computer, there are three notations:

Type Operator position Example Evaluation difficulty Parentheses requirement
Infix expression Between operands (human convention) A + B * C Needs to handle precedence and parentheses Needed
Prefix expression (Polish notation) Before the operands + A * B C A single pass is enough Not required
Postfix expression (Reverse Polish Notation) After the operands A B C * + A single pass is enough Not required

The biggest advantage of postfix and prefix expressions is that evaluation requires no consideration of operator precedence or parentheses; you only need to scan from left to right in order.


Infix-to-postfix algorithm (Shunting Yard algorithm idea)

The core algorithm for converting an infix expression to postfix uses a stack; the basic flow is as follows:

  1. Scan the infix expression from left to right
  2. On encountering an operand (number/letter), output it directly
  3. On encountering an operator, compare its precedence with the operator on top of the stack:
  4. If the operator on top of the stack has higher or equal precedence, pop it and output it
  5. Repeat this process until the current operator can be pushed onto the stack
  6. - If the operator on top of the stack has higher or equal precedence, pop it and output it - repeat this process until the current operator can be pushed onto the stack
    1. On encountering a left parenthesis, push it onto the stack directly
    2. On encountering a right parenthesis, keep popping operators from the top and outputting them until a left parenthesis is encountered (the left parenthesis itself is popped but not output)
    3. After scanning ends, pop the remaining operators from the stack and output them in order

    Example

    #include

    #include   /* isalnum function */

    #include

    #define MAX 100

    char

    stack

    [

    MAX

    ]

    ;

    int

    top

    =

    1

    ;

    void

    push

    (

    char

    c

    )

    {

    stack

    [

    ++

    top

    ]

    =

    c

    ;

    }

    char

    pop

    (

    )

    {

    return

    (

    top

    ==

    1

    )

    ?

    1

    :

    stack

    [

    top

    --

    ]

    ;

    }

    /* returns operator precedence: a larger number means higher precedence */

    int

    precedence

    (

    char

    op

    )

    {

       

    if

    (

    op

    ==

    '+'

    ||

    op

    ==

    '-'

    )

    return

    1

    ;

     

    /* addition and subtraction have the lowest precedence */

       

    if

    (

    op

    ==

    '*'

    ||

    op

    ==

    '/'

    )

    return

    2

    ;

     

    /* multiplication and division have higher precedence */

       

    if

    (

    op

    ==

    '^'

    )

    return

    3

    ;

                 

    /* exponentiation has the highest precedence */

       

    return

    0

    ;

     

    /* not an operator */

    }

    /* convert an infix expression to a postfix expression
       parameters: infix the input infix expression string
              postfix the output buffer for the postfix expression */

    void

    infixToPostfix

    (

    char

    infix

    ,

    char

    postfix

    )

    {

       

    int

    i

    =

    0

    ,

    j

    =

    0

    ;

       

    char

    c

    ;

       

    while

    (

    (

    c

    =

    infix

    [

    i

    ++

    ]

    )

    !=

    '\0'

    )

    {

           

    /* operand (letter or digit): output directly */

           

    if

    (

    isalnum

    (

    c

    )

    )

    {

                postfix

    [

    j

    ++

    ]

    =

    c

    ;

           

    }

           

    /* left parenthesis: push onto the stack directly */

           

    else

    if

    (

    c

    ==

    '('

    )

    {

                push

    (

    c

    )

    ;

           

    }

           

    /* right parenthesis: pop until a left parenthesis is encountered */

           

    else

    if

    (

    c

    ==

    ')'

    )

    {

               

    while

    (

    top

    !=

    1

    &&

    stack

    [

    top

    ]

    !=

    '('

    )

    {

                    postfix

    [

    j

    ++

    ]

    =

    pop

    (

    )

    ;

               

    }

                pop

    (

    )

    ;

     

    /* pop the left parenthesis '(', but do not output it */

           

    }

           

    /* operator: handle precedence */

           

    else

    {

               

    while

    (

    top

    !=

    1

    &&

                       precedence

    (

    stack

    [

    top

    ]

    )

    =

    precedence

    (

    c

    )

    &&

                       stack

    [

    top

    ]

    !=

    '('

    )

    {

                    postfix

    [

    j

    ++

    ]

    =

    pop

    (

    )

    ;

               

    }

                push

    (

    c

    )

    ;

           

    }

       

    }

       

    /* Pop all remaining operators from the stack */

       

    while

    (

    top

    !=

    1

    )

    {

            postfix

    [

    j

    ++

    ]

    =

    pop

    (

    )

    ;

       

    }

        postfix

    [

    j

    ]

    =

    '\0'

    ;

     

    /* End of string */

    }

    int

    main

    (

    )

    {

       

    char

    infix

    [

    ]

    =

    "A+B*C"

    ;

       

    char

    postfix

    [

    MAX

    ]

    ;

        infixToPostfix

    (

    infix

    ,

    postfix

    )

    ;

       

    printf

    (

    "Infix: %s\n"

    ,

    infix

    )

    ;

         

    /* Output: Infix: A+B*C */

       

    printf

    (

    "Postfix: %s\n"

    ,

    postfix

    )

    ;

       

    /* Output: Postfix: ABC*+ */

       

    return

    0

    ;

    }


    Postfix Expression Evaluation

    Postfix expression 5 3 + 2 * evaluation - step demonstration

    Step 1

    Read 5

    Number, push onto stack

    Stack: 5

    Step 2

    Read 3

    Number, push onto stack

    Stack: 5 3

    Step 3

    Read +

    Pop 3 and 5, compute 5+3=8, push result onto stack

    Stack: 8

    5+3=8

    Step 4

    Read 2

    Number, push onto stack

    Stack: 8 2

    Step 5

    Read *

    Pop 2 and 8, compute 8*2=16, push result onto stack

    Stack: 16

    8*2=16

    Result

    at the end

    Only 16 remains in the stack, which is the result

    Result = 16

    Postfix 53+2* = 16 (equivalent to infix (5+3)*2)

    Once we have the postfix expression, evaluation with a stack is very straightforward: push operands onto the stack, and when encountering an operator, pop two operands, compute, then push the result back.

    Example

    #include

    #include

    #include

    #define MAX 100

    int

    stack

    [

    MAX

    ]

    ;

    int

    top

    =

    1

    ;

    void

    push

    (

    int

    val

    )

    {

    stack

    [

    ++

    top

    ]

    =

    val

    ;

    }

    int

    pop

    (

    )

    {

    return

    stack

    [

    top

    --

    ]

    ;

    }

    /* Compute the value of a postfix expression
       Parameters: postfix postfix expression (operands are all single digits 0-9)
       Returns: the computed result of the expression */

    int

    evaluatePostfix

    (

    char

    postfix

    )

    {

       

    int

    i

    =

    0

    ;

       

    char

    c

    ;

       

    while

    (

    (

    c

    =

    postfix

    [

    i

    ++

    ]

    )

    !=

    '\0'

    )

    {

           

    /* Operand: convert to number then push onto stack */

           

    if

    (

    isdigit

    (

    c

    )

    )

    {

                push

    (

    c

    '0'

    )

    ;

     

    /* '3' converted to integer 3 */

           

    }

           

    /* Operator: pop two operands, compute, then push back */

           

    else

    {

               

    int

    b

    =

    pop

    (

    )

    ;

     

    /* Second operand (right operand) */

               

    int

    a

    =

    pop

    (

    )

    ;

     

    /* First operand (left operand) */

               

    switch

    (

    c

    )

    {

                   

    case

    '+'

    :

    push

    (

    a

    b

    )

    ;

    break

    ;

                   

    case

    '-'

    :

    push

    (

    a

    b

    )

    ;

    break

    ;

                   

    case

    '*'

    :

    push

    (

    a

    b

    )

    ;

    break

    ;

                   

    case

    '/'

    :

    push

    (

    a

    /

    b

    )

    ;

    break

    ;

               

    }

           

    }

       

    }

       

    return

    pop

    (

    )

    ;

     

    /* The last element in the stack is the final result */

    }

    int

    main

    (

    )

    {

       

    /* Postfix expression "23+5*" is equivalent to infix "(2+3)*5" = 25 */

       

    char

    postfix

    [

    ]

    =

    "23+5*"

    ;

       

    int

    result

    =

    evaluatePostfix

    (

    postfix

    )

    ;

       

    printf

    (

    "Postfix %s = %d\n"

    ,

    postfix

    ,

    result

    )

    ;

     

    /* Output: Postfix 23+5* = 25 */

       

    return

    0

    ;

    }

    When evaluating a postfix expression, the pop order of operands is critical: the one popped first isthe right operand(b), and the one popped later isthe left operand(a). This is especially important for asymmetric operations like subtraction and division; reversing the order leads to wrong results.


    Complete example: infix evaluation

    Chaining the two steps above lets us build a complete calculator: infix -> postfix -> evaluation.

    Example

    #include

    #include

    #define MAX 100

    /* Operator precedence helper function (as above), evaluation function (as above), conversion function (as above) */

    /* For brevity, the functions defined above are omitted here; include them when actually using this. */

    int

    main

    (

    )

    {

       

    char

    infix

    [

    ]

    =

    "5+3*2"

    ;

               

    /* Infix expression */

       

    char

    postfix

    [

    MAX

    ]

    ;

        infixToPostfix

    (

    infix

    ,

    postfix

    )

    ;

       

    /* Step 1: convert to postfix */

       

    printf

    (

    "Infix: %s\n"

    ,

    infix

    )

    ;

         

    /* Output: Infix: 5+3*2 */

       

    printf

    (

    "Postfix: %s\n"

    ,

    postfix

    )

    ;

       

    /* Output: Postfix: 532*+ */

       

    int

    result

    =

    evaluatePostfix

    (

    postfix

    )

    ;

     

    /* Step 2: evaluation */

       

    printf

    (

    "Result: %s = %d\n"

    ,

    infix

    ,

    result

    )

    ;

       

    /* Output: Result: 5+3*2 = 11 */

       

    return

    0

    ;

    }