c - Precedence of operators in infix to postfix conversion -


i'm creating program in c converts expression in infix form postfix form using reverse polish algorithm through stack implementation. however, i'm having trouble how incoming token having same precedence topmost element of stack should placed. example, given infix form: (a+b-c/d+e^f^2), postfix form should be: ab+cd/-ef2^^+. however, program outputs: ab+cd/-ef^2^+. think problem lies part of code:

while(priority(token) <= priority(top_elem(&s)) && !isstackempty(&s)){     x = pop(&s);     printf("%c", x); } push(&s, token); 

by way, part executes operator tokens ('+', '-', '', '/', '^) , open parenthesis. priority function returns 0 open parenthesis, 1 '+' , '-', 2 '' , '/', , 3 '^'.

i wondering should change in program. executes fine other inputs, though.

you have problem of associativity: while (a * b) * c == * (b * c) holds true, same not hold powerto (or ^): (a ^ b) ^ c != ^ (b ^ c).

you need resolve each operand when priorities match up:

while(!isstackempty(&s) &&       (priority(token) < priority(top_elem(&s)) ||        priority(token) == priority(top_elem(&s)) && !isrightasoc(token))) {     x = pop(&s);     printf("%c", x); } push(&s, token); 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -