Infix to prefix (expression)

Source: Internet
Author: User

Problem description:

Example of prefix fix:

(4 + 2) * (3 + 6) => * + 4 2 + 3 6

(3/4 + 2)-5 =>-+/3 4 2 5

(3 + 4/2)-5 =>-+ 3/4 2 5

If the expression is drawn into a tree structure, the prefix, infix, and suffix are the first, middle, and last traversal of the tree.

-----------------*------------------

------------/-----------\-----------

-------- + ---------------- + ---------

------/----\------------/-----\------

---- 4-------2---------3-------6 ----

 

Thought 1 (stack ):

1. Read from right to left

2. When a number is added to the output stream header, the stack is determined based on the priority when a symbol is encountered:

1) low entry is higher

2) Right parenthesis. the stack is output until the left parenthesis is encountered.

 

Idea 2 (brackets ):

1. infix: A + B * C-(D + E)

2. brackets are filled by priority: (a + (B * C)-(D + E ))

3. Move the operator to the beginning of brackets:-(+ (A * (BC) + (de ))

4. parentheses:-+ a * B C + D E

PS:

The suffix is similar to this, but only after the operators are transplanted to the corresponding brackets.

 

Idea 3 (tree ):

1. Change the infix to a tree structure (by operator priority)

2. traverse the tree structure in sequence

 

Reprinted, please indicate the reference from:

Http://www.cnblogs.com/breakthings/p/4051909.html

 

Infix to prefix (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.