What do Push and Pop mean for Stacks?

后端 未结 9 1104
臣服心动
臣服心动 2021-01-31 18:35

long story short my lecturer is crap, and was showing us infix to prefix stacks via an overhead projector and his bigass shadow was blocking everything so i missed the importan

9条回答
  •  死守一世寂寞
    2021-01-31 18:39

    The algorithm to go from infix to prefix expressions is:

    -reverse input
    
    TOS = top of stack
    If next symbol is:
     - an operand -> output it
     - an operator ->
            while TOS is an operator of higher priority -> pop and output TOS
            push symbol
     - a closing parenthesis -> push it
     - an opening parenthesis -> pop and output TOS until TOS is matching
            parenthesis, then pop and discard TOS.
    
    -reverse output
    

    So your example goes something like (x PUSH, o POP):

    2*3/(2-1)+5*(4-1)
    )1-4(*5+)1-2(/3*2
    
    Next
    Symbol  Stack           Output
    )       x )
    1         )             1
    -       x )-            1
    4         )-            14
    (       o )             14-
            o               14-
    *       x *             14-
    5         *             14-5
    +       o               14-5*
            x +             14-5*
    )       x +)            14-5*
    1         +)            14-5*1
    -       x +)-           14-5*1
    2         +)-           14-5*12
    (       o +)            14-5*12-
            o +             14-5*12-
    /       x +/            14-5*12-
    3         +/            14-5*12-3
    *       x +/*           14-5*12-3
    2         +/*           14-5*12-32
            o +/            14-5*12-32*
            o +             14-5*12-32*/
            o               14-5*12-32*/+
    
    +/*23-21*5-41
    

提交回复
热议问题