Conversion of InfixToPostfix
Sat Mar 11 2023 06:24:48 GMT+0000 (Coordinated Universal Time)
Saved by @solve_karbe12 #c
#include <stdio.h>
#include <stdlib.h>
#include<strings.h>
struct Node
{
char data;
struct Node *next;
}*top=NULL;
void push(char x)
{
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
if(t==NULL)
printf("stack is full\n");
else
{
t->data=x;
t->next=top;
top=t;
}
}
char pop()
{
struct Node *t;
char x=-1;
if(top==NULL)
printf("Stack is Empty\n");
else
{
t=top;
top=top->next;
x=t->data;
free(t);
}
return x;
}
int pre(char x)
{
if(x=='+' || x=='-')
return 1;
else if(x=='*' || x=='/')
return 2;
else if(x=='^')
return 3;
return 0;
}
int isOperand(char x)
{
if(x=='+' || x=='-' || x=='*' || x=='/'||x=='^'||x==')')
return 0;
else
return 1;
}
char *intopost(char infix[])
{
int i=0,j=0;
// push('(');
// strcat(infix,')');
char *postfix;
int len=strlen(infix);
postfix=(char*)malloc((len+2)*sizeof(char));
while(infix[i]!='\0')
{
if(infix[i]=='(')
push(infix[i++]);
else if(isOperand(infix[i]))
postfix[j++]=infix[i++];
else if(infix[i]==')')
{
char x=pop();
while(x!='(')
{
postfix[j++]=x;
x=pop();
}
i++;
}
else
{
if(top==NULL)
push(infix[i++]);
else if(pre(infix[i])>pre(top->data))
push(infix[i++]);
else
postfix[j++]=pop();
}
}
while(top!=NULL)
postfix[j++]=pop();
postfix[j]='\0';
return postfix;
}
int main()
{
int n;
scanf("%d",&n);
char infix[n];
for(int i=0;i<n;i++)
scanf("%c",&infix[i]);
int i=0,j=n-1;
while(i<j)
{
char temp=infix[i];
infix[i]=infix[j];
infix[j]=temp;
}
//printf("%s",infix);
char *postfix=intopost(infix);
i=0,j=n-1;
while(i<j)
{
char temp=postfix[i];
postfix[i]=postfix[j];
postfix[j]=temp;
}
for(int i=0;i<n;i++)
scanf("%c",postfix[i]);
// printf("%s ",postfix);
return 0;
}



Comments