Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* convert infix notation to postfix notation */
- #include<stdio.h>
- #include<string.h>
- char stackPop(char *, int *); //stack array and address of top.
- void stackPush(char *, char, int *); //stack array, element to push, address of top.
- void main()
- {
- int i, top = -1;
- char stack[100],infix[100],postfix[100],p;
- printf("Enter the infix expression: ");
- scanf("%s",infix);
- stackPush(stack,'(',&top);
- strcat(")",infix);
- i=0;
- while (top!=-1) //process stops when stack is empty.
- {
- if(infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/')
- {
- if (infix[i] == '+' || infix[i] == '-')
- {
- while(stack[top] == '+' || stack[top] == '-' || stack[top] == '*' || stack[top] == '/')
- {
- p = stackPop(stack, &top);
- postfix [strlen(postfix)] = p;
- }
- }
- else
- {
- while(stack[top] == '*' || stack[top] == '/')
- {
- p = stackPop(stack, &top);
- postfix [strlen(postfix)] = p;
- }
- }
- stackPush(stack,infix[i],&top);
- }
- else if(infix[i] == '(')
- stackPush(stack,infix[i],&top);
- else if(infix[i] == ')')
- {
- p = stackPop(stack,&top);
- while (p!= '(')
- {
- postfix [strlen(postfix)] = p;
- p = stackPop(stack,&top);
- }
- }
- else //for infix[i] == operand
- postfix [strlen(postfix)] = infix[i];
- i++;
- }
- printf("The postfix notation is %s", postfix);
- }
- void stackPush(char *stack, char item, int *top)
- {
- stack[++(*top)]=item;
- }
- char stackPop(char *stack, int *top)
- {
- int item = stack[(*top)--];
- return item;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement