int comput(const char *exp) { int i = 0; int ret; LinkStack *stack = LinkStack_Create(); for (i=0; exp[i] != '\0'; i++) { if ( isNumber(exp[i]) ) LinkStack_Push(stack, (void*)value(exp[i])); else if ( isOperator(exp[i]) ) { int right = (int)LinkStack_Pop(stack); int left = (int)LinkStack_Pop(stack); ret = express(left, right, exp[i]); LinkStack_Push(stack, (void*)ret); } else { break; } } if ( LinkStack_Size(stack)==1 && exp[i]=='\0') ret = (int)LinkStack_Pop(stack); else printf("invalid expression!\n"); LinkStack_Destroy(stack); return ret; }
void tranform(const char * exp) { int i = 0; LinkStack * stack = LinkStack_Create(); while ( exp[i] != '\0' ) { if ( isNumber(exp[i]) ) print(exp[i]); else if ( isOperator(exp[i]) ) { while (priority(exp[i]) <= priority((char)(int)LinkStack_Top(stack)) ) { print((char)(int)LinkStack_Pop(stack)); } LinkStack_Push(stack, (void*)(int)exp[i]); } else if ( isLeft(exp[i]) ) { LinkStack_Push(stack, (void*)(int)exp[i]); } else if ( isRight(exp[i]) ) { char c = 0; while ((c=(char)(int)LinkStack_Pop(stack)) != '(') print(c); } else { printf("invalid expression!\n"); break; } i++; } while ( LinkStack_Size(stack)>0 && exp[i]=='\0') print((char)(int)LinkStack_Pop(stack)); LinkStack_Destroy(stack); }
int scanner(const char *code) { int i = 0; int ret = 0; LinkStack *stack = LinkStack_Create(); while ( code[i] != '\0') { if ( isLeft(code[i]) ) LinkStack_Push(stack, (void*)(code+i)); if ( isRight(code[i]) ) { char* c = (char*)LinkStack_Pop(stack); if ( (c==NULL) || !match(*c, code[i]) ) { printf("%c does not match!\n", code[i]); ret = 0; break; } } i++; } if ( LinkStack_Size(stack)==0 && code[i]=='\0') { printf("success!\n"); ret = 1; } else { printf("failed!\n"); ret = 0; } LinkStack_Destroy(stack); return ret; }
int compute(const char* exp) { LinkStack* stack = LinkStack_Create(); int ret = 0; int i = 0; while (exp[i] != '\0') { if (isNumber3(exp[i])) { LinkStack_Push(stack, (void*)value(exp[i])); } else if (isOperator3(exp[i])) { int right = (int)LinkStack_Pop(stack); int left = (int)LinkStack_Pop(stack); int result = express(left, right, exp[i]); LinkStack_Push(stack, (void*)result); } else { printf("Invalid expression!"); break; } i++; } if ((LinkStack_Size(stack) == 1) && (exp[i] == '\0')) { ret = (int)LinkStack_Pop(stack); } else { printf("Invalid expression!"); } LinkStack_Destroy(stack); return ret; }
int grammarAnalyze(const char* line) { int ret = 0; if (line == NULL) return -1; int i = 0; LinkStack *stack = NULL; stack = LinkStack_Create(); if (stack == NULL) return -2; while (*(line + i) != '\0') { if (isalpha(line[i])) { i++; continue; } else if (isleft(line[i])) { LinkStack_Push(stack, (void *)&line[i]); } else if (isright(line[i])) { char *tmp; tmp = (char *)LinkStack_Pop(stack); if (tmp == NULL || !ismatch(*tmp, line[i])) { break; } } i++; } if (LinkStack_Size(stack) == 0 && line[i] == '\0') { ret = 1; } LinkList_Destroy(stack); return ret; }