I'm trying to understand a topic in class about using stacks and queues as a means of programming a calculator. I understand what infix and postfix expression is but how does it make it easier for a program to evaluate an expression and why are queues and stacks ideal in this situation? Thanks
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
It makes the order of operations simpler to handle, for example:
Can only mean
Which might be more readable for us, but we need to know the order of operations and match parentheses to figure it out.
As for implementing: if you had a stack, you could handle the expression above as follows:
+
(an operation), push it onto the stack,*
(an operation), push it onto the stack,-
(an operation), push it onto the stack,4
(a number), the top of the stack is not a number, so push it onto the stack.2
(a number), the top of the stack is a number, so pop from the stack twice, you get4 - 2
, calculate it (2
), and push the result (2
) onto the stack.5
(a number), the top of the stack is a number, so pop from the stack twice, you get2 * 5
, push the result (10
) onto the stack.3
(a number), the top of the stack is a number, so pop from the stack twice, you get3 + 10
, push the result (13
) onto the stack.13
).So as you can see, the expression was evaluated using a few simple rules and without having to search through the entire string for parentheses or having to decide whether multiplication has priority over addition and subtraction.