Home c++ Postfix Polish C++ notation

Postfix Polish C++ notation

Author

Date

Category

Given expression (-a) – (- b). Arrange the evaluation of this expression using the postfix Polish notation algorithm.

  • What will this stack record look like?
    – b 0 – a 0 (read from right to left)

  • Is an enchant or int put on the stack?

  • And how to make calculations?

Answer 1, authority 100%

How to store on the stack – in this case, there are two stacks. One for calculations, the other stores the Polish record itself (although this is no longer a stack, but just a queue).

The stack for calculations is best done of int or double (float) type.

It is better to write the computation itself in a regular vector of strings (although it is possible on the stack as well, as it is convenient). And store in “normal order” (that is, expand). That is, I would store this {"0", "a", "- '," 0 "," b "," - "," - "} .

How to do it. The code in the loop reads an element from the vector and looks at it. If this is a number (the first character is a digit) – pushes onto the computation stack, if it is a variable (a or b in your case, that is, the first character is a..z A..Z) – takes their value (for example, asks the user) and pushes it onto the stack. If there is an operation in the queue, then it pops two numbers from the stack, performs the operation and pushes the result of the calculations onto the stack. At the end of the job, the top of the stack is simply printed.

The actual code, I think you can write yourself.


Answer 2, authority 100%

What will this stack record look like? - b 0 - a 0 (read from right to left)

No. This entry is not on the stack. A record is an input sequence of commands. And it is always written from left to right!

Is there an enchant or int put on the stack?

When in a store do you estimate the cost of a purchase, add up the prices of goods or their names? If in life you always add numbers, where did the idea of ​​putting symbols on the stack come from?

And how to make calculations?

Sequentially execute the input sequence of commands!

Here it is: 0 a - 0 b - -

  1. Push 0
  2. Put the value of the number a there
  3. We take the last two numbers from the stack and subtract, the result is pushed back onto the stack
  4. Do the same with the 0 b - commands, the stack now contains numbers (-a) and (-b )
  5. We repeat the subtraction operation again, now there is only one number on the stack – the result of the expression
  6. We take it off the stack and show it to the user (or do something else, depending on what is required)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions