#include #include #include #include typedef struct node { int numdata; struct node * nextnode; } node; node * pushItem(node * stackTop, int number) { static node * newItem; newItem = calloc(sizeof(node),1); newItem->numdata = number; newItem->nextnode = stackTop; return newItem; } node * popItem(node * stackTop) { static node * temp; temp = stackTop->nextnode; free(stackTop); return temp; } void calculate(char * inString) { char * strPointer = inString; char numString[20]; int currentNum; int numLength; int assigned = 0; node * stackTop = NULL; if (strPointer[0] == '\n') return; while (strPointer[0] != '\0') { if (isdigit(strPointer[0])) { numLength = strspn(strPointer,"0123456789"); if (assigned) { stackTop = pushItem(stackTop, currentNum); } else assigned = 1; strncpy(numString, strPointer, numLength); numString[numLength]='\0'; currentNum = atoi(numString); strPointer+= numLength; } else { switch (strPointer[0]) { case '+': { if (stackTop != NULL) { currentNum+=stackTop->numdata; stackTop = popItem(stackTop); } else { printf("Error! Too many arithmetic operations.\n"); return; } } break; case '-': { if (stackTop != NULL) { currentNum=stackTop->numdata-currentNum; stackTop = popItem(stackTop); } else { printf("Error! Too many arithmetic operations.\n"); return; } } break; case '*': { if (stackTop != NULL) { currentNum*=stackTop->numdata; stackTop = popItem(stackTop); } else { printf("Error! Too many arithmetic operations.\n"); return; } } break; case '/': { if (stackTop != NULL) { currentNum=stackTop->numdata/currentNum; stackTop = popItem(stackTop); } else { printf("Error! Too many arithmetic operations.\n"); return; } } break; case ' ': break; case '\n': { if (stackTop == NULL) { printf("The result of the computation is: %d.\n",currentNum); return; } else { printf("Error! Too many numbers.\n"); while (stackTop != NULL) stackTop = popItem(stackTop); return; } } default: { printf("Error! Illegal input.\n"); while (stackTop != NULL) stackTop = popItem(stackTop); return; } } strPointer++; } } return; } int main(void) { char inString[50]; printf("Please input a polish postfix expression.\n\n> "); while (strcmp(fgets(inString,50,stdin),"quit\n")!=0) { calculate(inString); printf("> "); } return 0; }