Sunteți pe pagina 1din 3

C Program to implement Infix to Postfix Expression conversion algorithm

Program: #include<stdio.h> #include<stdlib.h> #include<string.h> struct node { char element; struct node *next; } *head; void push(char c); // function to push a node onto the stack char pop(); // function to pop the top node of stack int precedence(char c); // function to find the precedence of an operator void traceStack(); // function to //print the stack values int main() { int i = 0, j = 0; // indexes to keep track of current position for input output strings char *exp = (char *)malloc(sizeof(char)*100); char *res = (char *)malloc(sizeof(char)*100); char tmp; head = NULL; printf("Enter the infix expression: "); scanf("%s", exp); while( (tmp=exp[i++]) != '\0') { // repeat till the last null terminator // if the char is operand, copy it to output string if(tmp >= 97 && tmp <= 122) { res[j++] = tmp; continue; } if(tmp == '(' || tmp == '[' || tmp == '{') { push(tmp); continue; } if(tmp == ')' || tmp == ']' || tmp== '}') { char cl, tp; if(tmp == ')') cl = '('; if(tmp == '}') cl = '{'; if(tmp == ']') cl = '['; tp = pop(); while(tp != cl) {

res[j++] = tp; tp = pop(); } continue; } // if char is operator if(tmp == '+' || tmp == '-' || tmp == '*' || tmp == '/') { if(head == NULL) { push(tmp); } else { // if operator at top of stack has high precedence, pop it and // add to output string, else just push the operator while(precedence(tmp) <= precedence(head->element) && head->element != '(' && head->element != '[' && head->element != '{') { char tp = pop(); res[j++] = tp; if(head == NULL) break; } push(tmp); } } } // pop all the operators from stach to output string while (head != NULL) { res[j++] = pop(); }; res[j++] = '\0'; printf("Postfix expression is %s\n\n", res); return 0; } void push(char c) { if(head == NULL) { head = malloc(sizeof(struct node)); head->element = c; head->next = NULL; } else { struct node *tNode; tNode = malloc(sizeof(struct node)); tNode->element = c; tNode->next = head; head = tNode; } } char pop() { struct node *tNode;

tNode = head; head = head->next; return tNode->element; } int precedence(char c) { if (c == '*' || c == '/') return 2; else if (c == '+' || c == '-') return 1; else return 5; } void traceStack() { struct node *tNode; tNode = head; while(tNode != NULL) { printf("%c --> ", tNode->element); tNode = tNode->next; } printf("\n"); } Sample Output: Enter the infix expression: (a+b)*(d+e) Postfix expression is ab+de+* For more programs visit http://www.gethugames.in/blog

S-ar putea să vă placă și