Hey guys, i have a project to convert an Infix Expression to Postfix Expression or the Reverse Polish Notation.
I'm almost done but my code only reads single digits..
For example, if i input 12+3, it converts to 123+ and gives 5 as a result.
How do i read the number '12' as one so it can be 12 3 + = 15?
Here's my code..if you find something wrong with it please tell me too so i can fix it..
Code:
QUEUE head=NULL;
void push(STACK *top, char c)
{
STACK temp;
temp=(stacks*)malloc(sizeof(stacks));
temp->x= c;
temp->next = *top;
*top=temp;
}
void pop(STACK *top)
{
STACK temp;
if(!isEmpty(*top))
{
temp=*top;
if(temp->x!='(')
{
enqueue(&head,(*top)->x);
}
*top=(*top)->next;
free(temp);
}
}
void intPush(STACK2 *top, float a)
{
STACK2 temp;
temp=(stacks2*)malloc(sizeof(stacks2));
if(temp==NULL)
{
printf("no memory!");
}
temp->x= a;
temp->next = *top;
*top=temp;
}
float intPop(STACK2 *top)
{
STACK2 temp;
float valuePopped;
if(*top!=NULL)
{
temp=*top;
valuePopped=(*top)->x;
*top=(*top)->next;
free(temp);
}
return valuePopped;
}
void enqueue(QUEUE *head, char x)
{
QUEUE p;
QUEUE temp;
temp = (queues*) malloc(sizeof(queues));
if(*head==NULL)
{
temp->x = x;
temp->next = NULL;
*head=temp;
}
else
{
p=*head;
while(p->next!=NULL)
{
p=p->next;
}
temp->x = x;
temp->next = NULL;
p->next = temp;
}
}
void toRPN(STACK *top, char *x, STACK2 *top2)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hOut,FGI);
printf("\n\nIn Postfix Notation\n ");
while(*x!='\0')
{
if(*x=='(')
{
push(&(*top),*x);
}
else if(*x==')')
{
while(!isEmpty(*top) && (*top)->x!='(')
{
pop(&(*top));
}
if((*top)->x=='(')
{
pop(&(*top));
}
}
else if(isdigit(*x))
{
enqueue(&head,*x);
}
else
{
if(*x=='+' || *x=='-')
{
while(!isEmpty(*top) && priority((*top)->x)>0)
{
pop(&(*top));
}
push(&(*top),*x);
}
else if(*x=='*' || *x=='/' || *x=='%')
{
while(!isEmpty(*top) && priority((*top)->x)>1)
{
pop(&(*top));
}
push(&(*top),*x);
}
}
x++;
}
while(!isEmpty(*top))
{
pop(&(*top));
}
solve(&head, &(*top2));
}
float solve(QUEUE *head, STACK2 *top)
{
QUEUE p = *head;
float x;
float y;
float result;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
while(p!=NULL)
{
SetConsoleTextAttribute(handle,FCI);
printf("%c",p->x);
if(isalnum(p->x))
{
x = (float)atof(&(p->x));
intPush(&(*top),x);
}
else if(p->x!='(')
{
y=intPop(&(*top));
x=intPop(&(*top));
result = calculate(x,p->x,y);
intPush(&(*top),result);
}
p=p->next;
}
return (*top)->x;
}
int priority(char c)
{
if(c=='*' || c=='/' || c=='%')
return 2;
else if(c=='+' || c=='-')
return 1;
else
return 0;
}
bool isEmpty(STACK top)
{
if(top==NULL)
return true;
else
return false;
}
float calculate(float x, char op, float y)
{
if(op=='+')
return x + y;
else if(op=='-')
return x - y;
else if(op=='*')
return x * y;
else if(op=='/')
return x / y;
else if(op=='%')
return float((int)x % int(y));
else
return -1;
}