For this assignment you are to write a program which will ca
For this assignment, you are to write a program, which will calculate the results of Reverse Polish expressions that are provided by the user. You must use a linked list to maintain the stack for this program. You must handle the following situations (errors): Too many operators (+ -/*) Too many operands (doubles) Division by zero The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign. The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line. Your sample output should show the handling of all the error conditions as well as make use of all of the operators. Sample IO: Input Output 10 15 + = 25 10 15 - = -5 2.5 3.5 + = 6 (or 6.0) 10 0/= Error: Division by zero 10 20 */= Error: Too many operators 12 20 30/= Error: Too many operands -10 -30 - = 20 100 10 50 25/*--2/= -40 #include /* for atof() */ #define MAXOP 100 /* max size of operand or operator */ #define NUMBER \'0\' /* signal that a number was found */ int getop(char []); void push(double); double pop(void); main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case \'+\': push(pop() + pop()); break; case \'*\': push(pop() * pop()); break; case \'-\': op2 = pop(); push(pop() - op2); break; case \'/\': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf(\"error: zero divisor\ \"); break; case \'\ \': printf(\"\\t%.8g\ \", pop()); break; default: printf(\"error: unknown command %s\ \", s); break; } } } #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double f) { if(sp < MAXVAL) val[sp++]=f; else printf(\"error:stack full, cant push %g\ \",f); } double pop(void) { if(sp>0) return val[--sp]; else { printf(\"error: stack empty\ \"); return 0.0; } } #include int getch(void); void ungetch(int); int getop(char s[]) { int i,c; while((s[0] = c = getch()) == \' \' || c ==\'\\t\') ; s[1] = \'\\0\'; i = 0; if(!isdigit(c) && c!=\'.\' && c!=\'-\') return c; if(c==\'-\') if(isdigit(c=getch()) || c == \'.\') s[++i]=c; else { if(c!=EOF) ungetch(c); return \'-\'; } if(isdigit(c)) while(isdigit(s[++i] =c =getch())) ; if(c==\'.\') while(isdigit(s[++i] = c=getch())) ; s[i] = \'\\0\'; if(c!=EOF) ungetch(c); return NUMBER; } #define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { if(bufp >= BUFSIZE) printf(\"ungetch: too many characters\ \"); else buf[bufp++] = c; }
Solution
#include