how to write in reverse direction in c

184 views Asked by At

This is my first question so pardon for non technical language
I am making a program to convert infix to prefix and postfix. I made infix to postfix which is working. Now when I want to infix to prefix we need to reverse the expression. So I thought to read infix from reverse direction.

while(*e != '\0')
    {
        if(isalpha(*e))
            printf("%c ",*e);
        else if(*e == '(')
            push(*e);
        else if(*e == ')')
        {
            while((x = pop()) != '(')
                printf("%c ", x);
        }
        else
        {
            while(priority(stack[top]) >= priority(*e))
                printf("%c ",pop());
            push(*e);
        }
        e++;
    }  

Above is part of infix to postfix in which e is pointer which scans through string. In infix to pre I plan to replace e++ to e-- But as in first lines we see it prints the char directly so I need to reverse direction
Eg.
a
ba
+ba

1

There are 1 answers

1
Cow Corporation On

First, welcome to stackoverflow. (I am also new here.)

Actually, your title doesn't quite describe what you need: that is, "writing in reverse direction" is not sufficient for your goals.

Consider the input infix expression a + b * c. You've accomplished the sub-task of converting this to postfix as a b c * + (assuming the precedence of * is higher than +). A correct conversion to prefix would be + a * b c. Notice that this is not the same as a reversal of the postfix result (i.e., it is not + * c b a). To conclude, a prefix expression is not merely a reversal of a postfix expression.

So, how would I solve your task? I would create a system with three components. The first component processes your input and generates a simple "parse tree", which is graphically represented as:

  +  
 / \
a   *
   / \  
  b   c

The main data structure for this is a "parse tree node" that looks something like this:

struct Node {
    Node* leftChild;
    Node* rightChild;
    char symbol;
};

The second component converts from this parse tree into a postfix expression (accomplishing the same as what your original post did).

The third component converts from this parse tree into a prefix expression. To do so is simply a recursive process (given a particular node, output that node's symbol first, then recursively apply to the left side, then recursively apply to the right side). Please let me know if you need any further guidance on how to do this.