I am trying to transform a infix mathematical expression into a postfix expression using the shunting yard algortihm but can only get so far by writing the pseudo code because I know exactly what to do through logical thinking but can't write the code that will help me do it. If you can have a look at the code I wrote and help me in writing the code, I will really appreciate it.
Same with evaluating/calculating that postFix that was transformed. I also wrote the pseudo code for that function with the hope that someone will be able to help me.
This is my pseodo code:
Shunting Yard:
string shuntingYard(string expression)
{
string postFix = ""; //An initially empty array
int ops[]; //Array ops
int i = -1; //This will be an index into the array ops
while(/*tokens must still be read*/){
//Read next token from the expression
if(/*if the token is a constant or a variable*/)
{
//Append the token to the back of the postFix string
}
else if(/*the token is a function*/)
{
if(i == -1)
{
++i;
ops[i] = token;
}
}
else if(/*the token ia a operator*/)
{
if(i == -1)
{
++i;
ops[i] = token;
}
else
{
while(/*i > -1 && ops[i] is an operator && token is left-associative && its precedence <= to that of the operator at ops[i] or the token's precedence is < that of the operator at ops[i]*/)
{
//append ops[i] to the back of the postFix string;
--i;
}
if(i == -1)
{
++i;
}
ops[i] = token; //Place the operator at index i in ops
}
}
else if(/*token is a left-parenthesis*/)
{
if(i == -1)
{
++i;
}
//place the token at ops[i];
}
else //The token must be a right parenthesis
{
while(/*ops[i] is NOT a left parenthesis*/)
{
//append ops[i] to the back of the postFix string
--i;
}
//ops[i] at this point should be a left parenthesis
--i;
if(/*ops[i] is a function, append it to the postFix string*/)
{
--i;
}
}
}
while(i > -1)
{
//append ops[i] to the back of the postFix string;
--i;
}
//return the postFix string;
}
and this is the evaluation/calculation of the postfix expression:
int evaluate(string expr)
{
int operands[];
int i = -1;
while(/*expr still has tokens to read*/)
{
/*token = next token from expr;*/
if(/*If token is an integer or a variable*/){
operands[++i] = token;
}
else
{
if(/*Token is a binary operator*/)
{
//Retrieve the elements from the operands at indices i and i-1;
//Apply the operator to these operands;
//Place the answer at operands[i-1];
--i;
}
else //The token is a unary operator
{
//Retrieve the element at index i from operands;
//Apply the unary operator to this element;
//Place the answer at operands[i];
}
}
}
//The answer for the expression will be at operands[0];
}
Thank you very very much!
:)