Prefix expression solving

Source: Internet
Author: User

Problem description:

A prefix expression is also called a polish expression.

Example of prefix fix:

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

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

 

Thought 1 (recursion ):

1. Scan from left to right

2. Because the prefix expression contains binary operators without parentheses, operators can be solved recursively. For example, multiplication:

Case '*':

Return exp () * exp ();

 

Idea 2 (stack ):

1. Maintain the digital Stack

2. Scan from the right to the left. When a number is displayed, it is written into the stack. When a symbol is displayed, two numbers are generated. After calculation, the new number is reentered into the stack,The prefix expression and suffix expression are symmetric.So you can directly solve the problem in the opposite direction by the suffix method.

 

 

Reprinted, please indicate the reference from:

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

Prefix expression solving

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.