/*PROGRAM TO COMPUTE THE RESULT FOR A GIVEN POSTFIX EXPRESSION*/ #include #include #include #include #include struct st { int data; struct st *next; }; typedef struct st st; st *base,*newnode,*old; char operators[]={'+','-','*','/','%','\0'}; void push(int num) { if(base==NULL) { base=(st *)malloc(sizeof(st)); base->next=NULL; base->data=num; old=base; } else { newnode=(st *)malloc(sizeof(st)); newnode->next=NULL; newnode->data=num; old->next=newnode; old=newnode; } } int pop() { int num; st *temp; if(base==NULL) return(NULL); if(old==base) { num=base->data; free(base); base=NULL; } else { temp=old; old=base; while(old->next!=temp) old=old->next; num=temp->data; free(temp); } return(num); } int isoperator(char op) { int i; for(i=0;operators[i]!='\0';i++) { if(op==operators[i]) return(1); } return(0); } void accept(char ch,char *ipstr) { char *p; p=ipstr; while(1) { if(isdigit(ch)) { *p=ch; ch=getche(); p++; *p='\0'; } if(ch==' ') break; } } void main() { int num,op1,op2; char ch,ipstr[100]; clrscr(); printf("Program to evaluate a postfix expression\nSYMANTICS:\n\tSeperate data items\(strictly integers) with blank spaces\n\tHit return\(Enter\) to view result of the computation\n"); printf("\nEnter the postfix expression: "); base=NULL; while(1) { ch=getche(); if(ch==13) break; if(isdigit(ch)) { accept(ch,ipstr); num=atoi(ipstr); push(num); } if(isoperator(ch)) { op1=pop(); op2=pop(); if(op1==NULL||op2==NULL) { textcolor(WHITE+BLINK); printf("\n"); cprintf("\nERROR"); textcolor(7); printf("\nProbable causes:\n\tBad formatting/formulating or typing postfix expression\n\tStack overflow\n\tDivide error\nAborting. Press a key..."); getch(); exit(EXIT_FAILURE); } switch(ch) { case '+': num=op1+op2; break; case '-': num=op1-op2; break; case '*': num=op1*op2; break; case '/': num=op1/op2; break; case '%': num=op1%op2; break; default: printf("\nCondition not incorporated for operator.\nCheck operators array. \nAborting. Press a key..."); getch(); exit(EXIT_FAILURE); break; } push(num); } } num=pop(); printf("\nFinal answer of computation=%d",num); getch(); exit(EXIT_SUCCESS); }