4.2 Infix to Prefix

PHOTO EMBED

Fri Sep 01 2023 06:37:34 GMT+0000 (Coordinated Universal Time)

Saved by @109_Vivek

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

struct Node
{
	char data;
	struct Node* next;
};
struct Node* top=NULL;
struct Node* createNode(char ch)
{
	struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
	newNode->data=ch;
	newNode->next=NULL;
	return newNode;
}

void push(char data)
{
	if(top==NULL)
	{
		top=createNode(data);
	}
	else
	{
		struct Node* newNode=createNode(data);
		newNode->next=top;
		top=newNode;
	}
}


char pop()
{
	if(top==NULL)
	{
		printf("Stack is Empty");
		return '\0';
	}else
	{
		char temp=top->data;
		top=top->next;
		return temp;
	}
}

char peek()
{

	return top->data;
}

int prec(char op)
{
    switch (op)
    {
    case '+':
    case '-':
	return 1;
    case '*':
    case '/':
	return 2;
    case '^':
	return 3;
    }
    return -1;
}

void infixToPostfix(char *infix,char* postfix)
{
	int i=0;
	int j=0;
	while(infix[i]!='\0')
	{
		char c=infix[i];
		if((c>='a'&& c<='z') || (c>='A' && c<='Z'))
		{
			postfix[j++]=c;
		}
		else if(c=='(')
		{
			push(c);
		}
		else if(c==')')
		{
			while(peek()!='(')
			{
				postfix[j++]=peek();
				pop();
			}
			pop();
		}
		else
		{
			while((top!=NULL) && (peek()!='(')  && prec(peek())>=prec(c) )
			{
				postfix[j++]=pop();
			}
			push(c);
		}
		i++;
	}
	while(top!=NULL)
	{
		postfix[j++]=pop();
	}

}
int main()
{
	char infix[100]={'\0'},postfix[100]={'\0'};
	clrscr();
	printf("Enter Infix Expression : ");
	scanf("%s",&infix);
	infixToPostfix(infix,postfix);
	printf("%s",strrev(postfix));
	getch();
	return 0;
}
content_copyCOPY