#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stack
{
char stk[50][50];
int top;
};
typedef struct Stack stack;
void push(stack *p, char c)
{
p->top++;
p->stk[p->top][0] = c ;
p->stk[p->top][1] = '\0';
}
void puush(stack *p, char val[])
{
p->top++;
int i=0 , len = strlen(val);
for( i = 0; i< len ; i++)
p->stk[p->top][i] = val[i];
p->stk[p->top][i] = '\0';
}
void pop(stack *p)
{
p->top--;
}
char *top(stack *p)
{
return p->stk[p->top];
}
void print(stack *p)
{
int i = 0;
while(i <= p->top)
{
printf("index : %d elements : %s\n", i+1, p->stk[i]);
i++;
}
printf("\n");
}
int isOperand(char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return 1;
else return 0;
}
int isOperator(char c)
{
switch(c)
{
case '+':
case '-':
case '*':
case '/':
return 1;
default:
return 0;
}
}
void prefixToInfix(char s[])
{
stack s1;
s1.top = -1;
int i=0, len = strlen(s) - 1;
for(i = len ; i>= 0 ; i--)
{
if(isOperand(s[i]))
{
printf("%c\n\n",s[i]);
push(&s1, s[i]);
print(&s1);
}
if(isOperator(s[i]))
{
char concat[20];
int k,j= -1;
concat[++j] = '(';
char *c1 = top(&s1);
pop(&s1);
int len1 = 0;
len1 = strlen(c1);
for(k=0; k<len1; k++)
{
concat[++j] = c1[k];
}
concat[++j] = s[i];
c1 = top(&s1);
len1 = strlen(c1);
pop(&s1);
for(k= 0; k<len1; k++)
concat[++j] = c1[k];
concat[++j]=')';
concat[++j] = '\0';
printf("gnerated %s\n",concat);
puush(&s1, concat);
print(&s1);
}
}
printf("%s",top(&s1));
}
int main()
{
prefixToInfix("*-A/BC-/AKL");
}
Please help me, I am not getting the correct output as it should be. I am sharing my code thus it will be easier for you all to understand the problem of my Code
Explanation of my problem:
I have been trying to write a code which converts The Prefix form to Infix. I am getting the output as I expected except one extra parenthesis at last: For example:
The Input: "*-A/BC-/AKL"
Expected Output: ((A-(B/C))*((A/K)-L)
However my Program output:
((A-(B/C))*((A/K)-L)(, the last extra parenthesis is the issue "("