Anyone have a good source for the algorithms to convert infix/prefix/postfix?
Printable View
Anyone have a good source for the algorithms to convert infix/prefix/postfix?
What exactly are you referring to? Tree trasversals or string manipulation or what?
algorithm using stacks to input an expression in infix/postfix/prefix and output the conversions. I think there is a mistake or a part I don't quite understand for one of my algoritms. I'm particularly looking for prefix to infix.
Can you post some code maybe? I've done things like this (converting a mathematical string to prefix, postfix, infix etc), but without seeing how you went about it, I can't help you much.
HERE is source written in python that does the conversion as well as some discussion around the code. Is this what you're looking for?
Also, for those of you who don't know what's going on here, read this.
I figured it out from my algorithm, it just wasn't very clear because there are no braces and I didn't add a push where is was supposed to be. I simply had to move a brace.
This was the algorithm
this is the codeCode:set stack empty
repeat
read(char)
if char in operator then
push char onto stack
else
if stacktop is an operand then
repeat
pop stack to x
pop stack to y
w = concatenate('(',x,y,char,')')
move w to char
until ((stack is empty) or (stacktop is an operator))
push char onto stack
until (end of input)
pop stack to get the final answer
I may have added a couple things to make it easier for me to understand. This is only 1 method and doesn't show the stack class.Code:
public static void PreToIn(String pre){
String x, y;
String newString = "";
ArrayStack MyStack = new ArrayStack(20);
String topStack = "", character = "";
int i = 0, j = 1;
while(j <= pre.length()){
character = pre.substring(i,j);
topStack = MyStack.pop();
MyStack.push(topStack);
if(isOperator(character) == true){
MyStack.push(character);
topStack = MyStack.pop();
MyStack.push(topStack);
}
if(isOperator(topStack) == false){
while((isOperator(topStack) == false) || topStack == null){
x = MyStack.pop();
y = MyStack.pop();
newString = "(" + "(" + x + y + character + ")" + ")";
character = newString;
topStack = MyStack.pop();
}
}
MyStack.push(character);
i++;
j++;
}
System.out.println(MyStack.pop());
}
In case anyone cares, that algorithm and method are both wrong. I fixed them today.
I'll the first to admit I didn't read or try your code ;)Quote:
Originally posted by puff_1
In case anyone cares, that algorithm and method are both wrong. I fixed them today.
Glad you got it working, though.
That's cool, I typically won't read other people's code either. Someone asked for it though, so I posted it.Quote:
Originally posted by rock
I'll the first to admit I didn't read or try your code ;)
Glad you got it working, though.