-
convert infix to postfix
Hi everyone.I got problem about my homework which contains converting to infix to postfix.
For example : if the user enters 5*6+8/4 as infix, its postfix will be 57*84/+
Here is my code bu it doesn't work and I couldn't understand where my fault is.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct yapi{
char data;
struct yapi *next;
};
typedef struct yapi *stack;
void push(stack ptr,char x);
char pop(stack ptr);
int priority(char x) ;
void infixtopostfix(char *infix,char *postfix,stack ptr);
int main()
{
char in[50],post[50];
stack header;
header=(stack)malloc(sizeof(struct yapi));
header->next=NULL;
printf("Enter infix expression\n");
scanf("%s",in);
infixtopostfix(&in[0],&post[0],header);
printf("Postfix expression is %s\n",post);
system("pause");
return 0;
}
void push(stack ptr,char x){
stack newnode;
newnode=(stack)malloc(sizeof(struct yapi));
newnode->next=ptr->next;
newnode->data=x;
ptr->next=newnode;
}
char pop(stack ptr){
stack current;
char value;
ptr->next=current;
value=current->data;
ptr->next=ptr->next->next;
free(current);
return value;
}
int priority(char x){
int pri=0;
if(x=='+' || x=='-'){
pri=1;
}
if(x=='*' || x=='/'){
pri=2;
}
return pri;
}
void infixtopostfix(char *infix,char *postfix,stack ptr){
char *i,*p;
char character;
i=&infix[0];
p=&postfix[0];
while(*i!='\0')
{
if(isdigit(*i) || isalpha(*i)){
*p=*i;
p++;
i++;
}
if(*i=='+' || *i=='-' || *i=='*' || *i=='/')
{
if(ptr->next==NULL)
{
push(ptr,*i);
}
else
{
character=pop(ptr);
if(priority(character)>=priority(*i))
{
*p=character;
p++;
push(ptr,*i);
}
else{
push(ptr,character);
push(ptr,*i);
}
}
i++;
}
}
while(ptr->next!=NULL){
*p=pop(ptr);
p++;
}
*p='\0';
}
-
Your compiler is giving you a big hint:
Code:
$ gcc -o i2p i2p.c -Wall -Wextra
i2p.c: In function ‘pop’:
i2p.c:36: warning: ‘current’ is used uninitialized in this function