Here is my new working code. Man, working with strings in C is tedious and annoying. I had built the algorithm in short time, took hours figuring how to implement it properly in C. Tell me if there are more bugs or if some improvement is possible.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
char data[100];
struct node *next;
}SNode;
typedef struct{
int count;
SNode *top;
}stack;
int isEmpty(stack *s){
return (s->count==0);
}
void push(stack *s,char x[]){
SNode *temp = (SNode *)malloc(sizeof(SNode));
strcpy(temp->data,x);
temp->next = s->top;
s->top=temp;
s->count++;
}
char * pop(stack *s){
if(isEmpty(s)){
return "-1";
}
SNode *temp = s->top;
s->top = temp->next;
static char a[10];
strcpy(a,temp->data);
free(temp);
s->count--;
return a;
}
int main(){
stack *s = (stack *)malloc(sizeof(stack));
s->count = 0;
char a[100];
printf("Enter prefix expression: ");
gets(a);
int i;
for(i=strlen(a)-1;i>=0;i--){
if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/'){
char s1[10], s2[10];
strcpy(s1,pop(s));
strcpy(s2, pop(s));
char b1[10] ="(",b2[10]=")";
strcat(b1,s1);
char t[2]="\0";
t[0]=a[i];
strcat(b1,t);
strcat(b1,s2);
strcat(b1,b2);
push(s,b1);
}
else if(isalpha(a[i])){
char t[2] = "\0";
t[0] = a[i];
push(s,t);
}
}
char *infix = pop(s);
printf("Infix expression: %s",infix);
return 0;
}
*+ab+cd
should be(a+b)*(c+d)
and nota + b * c + d
\$\endgroup\$*+ab+cd
is equivalent tomult(add(a,b),add(c,d))
which comes out to(a + b) * (c + d)
. Prefix notation does not utilize parentheses en.wikipedia.org/wiki/Polish_notation \$\endgroup\$gets
for anything. \$\endgroup\$