Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "expeval.h"
- void InfixToPostfix(char *infixstr, char *postfixstr) {
- stack *top = NULL;
- char *p = infixstr, *p2 = postfixstr, temp;
- strcat(infixstr,")");
- push(&top, '(');
- while(*p != '\0'){
- if(*p == '('){
- push(&top, *p);
- } else if (isdigit(*p) || isalpha(*p)){
- *p2 = *p;
- p2++;
- } else if (*p == ')'){
- temp = peek(top);
- pop(&top);
- while(temp != '('){
- *p2 = temp;
- p2++;
- temp = peek(top);
- pop(&top);
- }
- } else if (isoper(*p)){
- temp = peek(top);
- pop(&top);
- while(isoper(temp) && getPriority(temp) > getPriority(*p)){
- *p2 = temp;
- p2++;
- temp = peek(top);
- pop(&top);
- }
- push(&top, temp);
- push(&top, *p);
- }
- p++;
- }
- while(top != NULL){
- temp = peek(top);
- pop(&top);
- *p2 = temp;
- p2++;
- }
- }
- int evaluatePostfix(char *exp) {
- stack *top = NULL;
- char *p = exp;
- int a, b;
- strcat(exp,")");
- while(*p != '\0'){
- if(isdigit(*p) || isalpha(*p)) push(&top, *p - '0');
- else if (isoper(*p)){
- a = peek(top);
- pop(&top);
- b = peek(top);
- pop(&top);
- if(*p == '^' ){
- push(&top, pow(b,a));
- } else if (*p == '*'){
- push(&top, b * a);
- } else if (*p == '/'){
- push(&top, b / a);
- } else if (*p == '+') {
- push(&top, b + a);
- } else if (*p == '-') {
- push(&top, b - a);
- }
- }
- p++;
- }
- return peek(top);
- }
- int getPriority(char op) {
- if (op == '/' || op == '*' || op == '%') return 1;
- else if (op == '+' || op == '-') return 0;
- return 0;
- }
- //A function to act like isdigit() or isalpha() to tell is a character is an operator
- int isoper(char c){
- if(c == '^' || c == '*' || c == '/' || c == '+' || c == '-') return 1;
- else return 0;
- }
- -------------------------------------------------------------------------------
- #include "stack.h"
- void push(stack **topp, int val) {
- stack *ptr = (stack *)malloc(sizeof(stack));
- ptr-> data = val;
- if (*topp == NULL) {
- ptr->next = NULL;
- *topp = ptr;
- } else {
- ptr -> next = *topp;
- *topp = ptr;
- }
- }
- void pop(stack **topp) {
- if (*topp == NULL) {
- printf("STACK UNDERFLOW \n");
- } else {
- stack *temp = *topp;
- *topp = temp->next;
- free(temp);
- }
- }
- int peek(stack *top) {
- if (top == NULL) {
- printf("STACK IS EMPTY \n");
- return -1;
- }
- else {
- return top->data;
- }
- }
- void clean(stack **topp) {
- node *temp, *np = *topp;
- while (np != NULL) {
- temp = np;
- np = np->next;
- free(temp);
- }
- *topp = NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement