How do I reverse a mathematical infix expression in C?

Viewed 52

I am trying to convert an infix expression into a prefix expression, that is from:

Input ~ 99+(88-77)*(66/(55-44)+33)

to

Output ~ + 99 * - 88 77 + / 66 - 55 44 33.

I have solved this test case but realised my code was erroneous because I had used the standard swap function to perform the reversal. That is:

void swap (int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

However, I realised using this function meant that I am reversing the order within the number itself as well. That is 12 + 13 - 14 / 15 becomes 51 / 41 - 31 + 21, which is not what I want.

I have tried googling, and someone mentioned making use of a stack/queue to try to push the numbers in order. I understand how that works but I am awful at scanning input in C. I don't understand how I should scan and push the numbers and operators into my output string.

Thank you for reading my post and for any advice rendered.

0 Answers
Related