C++ Implement a program for evaluating infix expressions. The program should rea
ID: 3569208 • Letter: C
Question
C++
Implement a program for evaluating infix expressions. The program should read an infix expression from a text file, check if the parentheses in the input expression are balanced, convert the infix expression into a postfix express ion, and then evaluate the postfix expression.
Explanation / Answer
#include #include #include #include #include #include #define MAX 5 struct node { char data; struct node *next; }; class stack { public: node *top; stack() //constructor { top=NULL; } char Top() //return top element without popping { return(top->data); } int empty() //check empty { if(top==NULL) return(1); return(0); } void push(char x) //push function { node *p; p=new node; p->data=x; p->next=top; top=p; } char pop() //pop function { node *p; char x; p=top; top=top->next; x=p->data; delete(p); return(x); } int precedence(char x) //check precedence of operators { if(x=='(') return 0; else if(x=='+'||x=='-') return 1; else if(x=='*'||x=='/'||x=='%') return 2; return 3; } void infix_to_postfix(char infix[],char postfix[]); }; void infix_to_postfix(char infix[],char postfix[]) { stack s; char x,token; int i,j=0; for(i=0;infix[i]!='';i++) { token=infix[i]; if(isalnum(token)) postfix[j++]=token; else if(token=='(') s.push(token); else if(token==')') { while((x=s.pop())!='(') postfix[j++]=x; } else { while(s.precedence(token)Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.