I'm working on a project that involves converting an infix equation to a postfix, and am having problems. If the precedence of the top elementof stack is not greater, it seems to work, but if it is, its dropping the last operator (ie doesnt print, and doesnt show up at the pop at end of function).
Algorithm used:
1) If is digit, send to postfix string.
2) If operator:
a) If stack empty, push
b) Else, use top to get copy of top stack element, compare to token. If stackVal has higher precedence, pop stack and repeat step 2.
c) Else push operator.
Tried using while loop for repeating step 2, only way I could get it to not go in an infinite loop is to add the !isEmpty(&st) to the conditions.
This is only the part that does the conversion:
Code:
static char postfix[BUFLEN]
static int curTok = 0;
static int nxtTok = 1;
void intopost(char buffer[])
{
STACK st;
int i, j, result = 0;
char temp;
initStack (&st);
curTok = 0;
nxtTok = 1;
for (i = 0, j = 0; i < strlen(buffer); i++)
{
if (isdigit(buffer[i]))
{
postfix[curTok++] = buffer[i];
}
else
{
if (isEmpty(&st))
{
push(&st, buffer[i]);
}
else
{
do
{
top(&st, &temp);
result = preCheck(temp, buffer[i]);
if (result == 1)
{
pop(&st, &postfix[curTok++]);
top(&st, &temp);
printf("TopVal: %c\n", temp);
}
}
while ((result != 0) && (!isEmpty(&st)));
if (result == 0)
{
push(&st, buffer[i]);
}
}
}
}
while(!isEmpty(&st))
{
pop(&st, &postfix[curTok++]);
}
postfix[curTok++] = '\0';
printf("%s\n", postfix);
}
int preCheck(char stackVal, char tokenVal)
{
int sval = 0, tval = 0;
switch(stackVal)
{
case '(':
case ')':
sval = 0;
break;
case '+':
case '-':
sval = 1;
break;
case '*':
case '/':
sval = 2;
break;
}
switch(tokenVal)
{
case '(':
case ')':
tval = 0;
break;
case '+':
case '-':
tval = 1;
break;
case '*':
case '/':
tval = 2;
break;
}
printf("stackVal: %d\n", sval);
printf("tokenVal: %d\n", tval);
if (sval > tval)
{
return(1);
}
else
{
return(0);
}
return(0);
}