Ck Tech

This website keeps you uptodate for technology, education and many more things.

Breaking

Friday, 11 November 2022

Infix To postfix

#include<iostream>
#include<string.h>
using namespace std;
struct stack{
	char data;
	stack* next;
};
stack* top=new stack;
void push(char data){
	stack* temp=top;
	stack* newnode=new stack;
	newnode->data=data;
	if(temp==NULL){
		top=newnode;
		newnode->next=NULL;	
	}
	else{
		newnode->next=top;
			top=newnode;
	}
}
void pop(){
stack* temp=top;
if(temp==NULL){
	cout<<"\nStack underflow\n";
}
else{
	top=temp->next;
	delete temp;
}
}
int isEmpty(){
	stack* temp=top;
	if(temp==NULL){
		return 1;
	}
	else
	return 0;
}
char Top(){
	stack*temp=top;
	return temp->data;
}
void display(){
	stack* temp=top;
	if(temp==NULL){
		cout<<"\nStack is empty\n";
	}
	else{
while(temp->next!=NULL){
	cout<<temp->data;
	temp=temp->next;
}
cout<<temp->data<<endl;
}
}



//Functions
int isOperator(char c){
	if(c=='+'||c=='-'||c=='*'||c=='/')
	return 1;
	else
	return 0;
}
int isOperand(char c){
	if(c>='a'&&c<='z')
	return 1;
	if(c>='A'&&c<='Z')
	return 1;
	if(c>='0'&&c<=9)
	return 1;
	else
	return 0;
}
int prec(char c){
	if(c=='^')
	return 3;
	else if(c=='*'||c=='/')
	return 2;
	else if(c=='+'||c=='-')
	return 1;
	else
	return 0;
}
int eqlorhigher(char op1,char op2){
	int p1=prec(op1);
	int p2=prec(op2);
	if (p1 == p2)  
{  
if (op1 == '^' )  
return false;  
return true;  
}  
	return (p1>p2?1:0);
}
string convert(string infix){
	string postfix="";
	char ch='(';
	push(ch);
	infix+=')';
	for(int i=0;i<infix.length();i++){
		ch=infix[i];
		if(ch==' ')
		continue;
		else if(ch=='(')
		push(ch);
		else if(isOperand(ch)){
			postfix+=ch;
		}
		else if(isOperator(ch)){
			while(!isEmpty()&&eqlorhigher(Top(),ch)){
				postfix+=Top();
				pop();
			}
			push(ch);
		}
		else if(ch==')'){
			while(!isEmpty()&&Top()!='('){
				postfix+=Top();
				pop();
			}
			pop();
		}
		
	}
	return postfix;
}
int main(){
string infix,postfix;
cout<<"Enter infix expression:";
cin>>infix;
postfix=convert(infix);
cout<<"\npostfix="<<postfix;
cout<<Top();
//display();
return 0;
}

No comments:

Post a Comment

Adbox