I need to evaluate prefix using a queue (not stack). for example:
+ 3 * 2 1
is equivalent to 3+(2*1) = 5.
I am thinking about to loop through the queue over and over using dequeue and enqueue. If the pattern "operator" + "number" + "number" if found, dequeue 3 times and enqueue the result until there is only a number left in the queue.
while size(q)>1
if elements are in this pattern: an operator is followed by 2 numbers.
operator <--dequeue(q);
number1 <--dequeue(q);
number2 <--dequeue(q);
int a = apply(operator, number1, number2 );
enqueue (q, a);
else if the element is a number or operator:
element <-- dequeue(q);
enqueue (q, element);
return dequeue(q);
My algorithm has 2 problems:
- operators and numbers are 2 different types and need to be saved in one queue. how can I save a "+" in an int queue?
- 2 3 + is an invalid input, but it will eventually return 5. 2 and 3 will be enqueued to the right, it becomes + 2 3. If the input is invalid, how do I prevent it?
Many thanks