infixtoprefix

hello
mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.3 kB
4
Indexable
Never
#include <stdio.h>
#include <conio.h>
#include <string.h>

char stack[20];
int top=-1;

void push(char);
void pop();
char topp();
int isempty();
int isfull();
int isoperator(char);
int isoperand(char);
int hashigherprecedence(char, char);
int operatorweight(char);
void infixtoprefix(char[], int);
int isleftorrightassociative(char);
void init(char[]);

int main()
{
	char infixexpr[20];
	printf("\n Enter and infix expression :\n"); gets(infixexpr);
	infixtoprefix(infixexpr, strlen(infixexpr));
}

void infixtoprefix(char infixexpr[], int len)
{
	int i,j=0;
	char res[20];
	char k,m;
	printf("\n\n %s\n\n", res);
	init(res);
	printf("\n\n %s \n\n", res);
//	strrev(infixexpr[]);
	for(i=0; i<len; i++)
	{
		k=infixexpr[i];
		if(isoperand(k))
		{
			res[j++]=k; continue;
		}
		else if(isoperator(k))
		{
			while(!isempty() && hashigherprecedence(topp(),k))
			{
				m=topp;
				pop();
				res[j++]=m;
			}
			push(k);
		}
	}
	while(!isempty())
	{
		m=topp();
		pop();
		res[j++]=m;
	}
	res[j]= '\0';
	printf("\nPostfix: %s\n\n", res); getch();
	
}
void init(char s[])
{
	int i;
	for(i=0; i<20; i++)
	{
		s[i]='a';
	}
}
void push(char c)
{
	if(isfull())
	{
		printf("\n Stack is full! \n"); getch(); return;
	}
	stack[++top]=c;
}


void pop()
{
	if(isempty())
	{
				printf("\n Stack is empty! \n"); getch(); return;

	}
	top--;
}
char topp()
{
	if(isempty())
	{
				printf("\n Stack is empty! \n"); getch(); return 'z';

	}
	return stack[top];
}
int isempty()
{
	return(top==-1)?1:0;
}
int isfull()
{
	return (top==19)?1:0;
}
int isoperator(char c)

{
	if(c=='^' || c=='*' || c=='/' || c=='+' || c=='-' ) return 1;
	else return 0;
}

int isoperand(char c)
{
	if(c>='0' && c<='9') return 1;
	if(c>='a' && c<='z') return 1;
	if(c>='A' && c<='Z') return 1;
	return 0;
}

int hashigherprecedence(char c,char k)
{
	int cweight=operatorweight(c);
	int kweight=operatorweight(k);
	if(cweight==kweight)return 1;
	if(cweight> kweight)return 1;
	return 0;
}

int isleftorrightassociative(char c)
{
	if(c=='^') return 0;
	return 1;
}

int operatorweight(char c)
{
	int wt;
	switch(c)
	{
		case '^': wt=3; break;
		case '*':
		case '/': wt=2; break;
		case '+':
		case '-': wt=1; break;
	}
	return wt;
}