Learn Infix to Prefix with a step-by-step Stacks & Queues visualizer, JavaScript source code and a worked example. Practice operations and expressions.
INTERACTIVE EXECUTION STUDIO
LEARN BY DOING
Predict. Execute. Understand.
Follow the source code, inspect live state changes, and predict the next operation before revealing it.
Topic: Stacks & Queues · Operations and expressions
Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.
Example input
{
"input": "a+b*c",
"mode": "pre"
}
Execution steps
Read token a
Read token +
Read token b
Read token *
Read token c
Flush operators
Build prefix expression
Computed output
"+a*bc"
JavaScript reference implementation
const solve = ({
input,mode
},s)=>{
let stack=[],o=[],rank={
"+":1,"-":1,"*":2,"/":2
};
for(let x of input){
if(/[a-z]/.test(x))o.push(x);
else if(x==="(")stack.push(x);
else if(x===")"){
while(stack.at(-1)!=="(")o.push(stack.pop());
stack.pop()
}else{
while(stack.length&&rank[stack.at(-1)]>=rank[x])o.push(stack.pop());
stack.push(x)
}
s("Read token "+x,{
Operators:stack,Postfix:o
})
}
while(stack.length){
o.push(stack.pop());
s("Flush operators",{
Operators:stack,Postfix:o
})
}
if(mode==="post")return o.join("");
let a=[];
for(let x of o){
if(/[a-z]/.test(x))a.push(x);
else{
let r=a.pop(),l=a.pop();
a.push(x+l+r)
}
s("Build prefix expression",{
Stack:a
})
}
return a[0]
};